基于.net framework4.0框架下winform项目实现寄宿式web api

首先Nuget中下载包:Microsoft.AspNet.WebApi.SelfHost,如下:

注意版本哦,最高版本只能4.0.30506能用。

1.配置路由

public static class WebApiConfig{public static void Register(this HttpSelfHostConfiguration config){// 配置JSON序列化设置config.Formatters.Clear();config.Formatters.Add(new JsonMediaTypeFormatter());config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();// 配置路由//config.MapHttpAttributeRoutes();config.Routes.Clear();config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });}}

路由器不要搞错了,其实和老版本asp.net 差不多。

2.创建一个控制器

public class ValuesController : ApiController{[HttpGet]public string HelloWorld(){return "Hello World!";}[HttpGet]public ModelTest Test(){var model = new ModelTest();model.Id = Guid.NewGuid().ToString();model.Name = "Test";return model;}[HttpGet]public List<ModelTest> Test2(){List<ModelTest> modelTests = new List<ModelTest>();for (int i = 0; i < 3; i++){var model = new ModelTest();model.Id = Guid.NewGuid().ToString();model.Name = "Test";modelTests.Add(model);}return modelTests;}}

 创建一个WebServer,以来加载实现单例

public class WebServer{private static Lazy<WebServer> _lazy = new Lazy<WebServer>(() => new WebServer());private ManualResetEvent _webEvent;private WebServer(){}public static WebServer Instance => _lazy.Value;public string BaseAddress { get;set; }public Action<WebServer> StartSuccessfulCallback { get; set; }public Action<WebServer> RunEndCallback { get; set; }public Action<WebServer, AggregateException> StartExceptionCallback { get;set; }public void StartWebServer(){if (string.IsNullOrEmpty(BaseAddress)) return;_webEvent=new ManualResetEvent(false);Task.Factory.StartNew(() =>{HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(BaseAddress);config.Register();using (HttpSelfHostServer server = new HttpSelfHostServer(config)){try{server.OpenAsync().Wait();if (StartSuccessfulCallback != null)StartSuccessfulCallback(this);_webEvent.WaitOne();if (RunEndCallback != null)RunEndCallback(this);}catch (AggregateException ex){_webEvent.Set();_webEvent.Close();_webEvent = null;if (StartExceptionCallback != null)StartExceptionCallback(this,ex);}finally{server.CloseAsync().Wait();server.Dispose();}}});}public void StopWebServer(){if (_webEvent == null) return;_webEvent.Set();_webEvent.Close();}}

public class WebApiFactory{static string baseAddress = "http://localhost:9000/";static WebApiFactory(){Server = WebServer.Instance;Server.BaseAddress = baseAddress;}public static WebServer Server { get;private set; }}

 使用

public partial class Form1 : Form{public Form1(){InitializeComponent();WebApiFactory.Server.StartSuccessfulCallback = (t) =>{label1.Text = "Web API hosted on " + t.BaseAddress;};WebApiFactory.Server.RunEndCallback = (t) =>{label1.Text = "Web API End on " + t.BaseAddress;};WebApiFactory.Server.StartExceptionCallback = (t,ex) =>{MessageBox.Show(string.Join(";", ex.InnerExceptions.Select(x => x.Message)));};}private void button1_Click(object sender, EventArgs e){WebApiFactory.Server.StartWebServer();}private void button2_Click(object sender, EventArgs e){WebApiFactory.Server.StopWebServer();}private void Form1_FormClosing(object sender, FormClosingEventArgs e){WebApiFactory.Server.StopWebServer();}}

注:启动时必须以管理员身份启动程序

 我们挂的是http://localhost:9000/,接下来我们去请求:http://localhost:9000/api/Values/Test2

扩展:简单添加权限验证,不通过路由

public class BasicAuthorizationHandler : DelegatingHandler{protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){if (request.Method == HttpMethod.Options){var optRes =  base.SendAsync(request, cancellationToken);return optRes;}if (!ValidateRequest(request)){var response = new HttpResponseMessage(HttpStatusCode.Forbidden);var content = new Result{success = false,errs = new[] { "服务端拒绝访问:你没有权限" }};response.Content = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");var tsc = new TaskCompletionSource<HttpResponseMessage>();tsc.SetResult(response); return tsc.Task;}var res =  base.SendAsync(request, cancellationToken);return res;}/// <summary>/// 验证信息解密并对比/// </summary>/// <param name="message"></param>/// <returns></returns>private bool ValidateRequest(HttpRequestMessage message){var authorization = message.Headers.Authorization;//如果此header为空或不是basic方式则返回未授权if (authorization != null && authorization.Scheme == "Basic" && authorization.Parameter != null){string Parameter = authorization.Parameter;// 按理说发送过来的做了加密,这里需要解密return Parameter == "111";// 身份验证码}else{return false;}}}/// <summary>/// 构建用于返回错误信息的对象/// </summary>public class Result{public bool success { get; set; }public string[] errs { get; set; }}

然后在WebApiConfig中注册

// 注册身份验证
config.MessageHandlers.Add(new BasicAuthorizationHandler());

根据自己需求做扩展吧,这里由于时间问题简单做身份验证(全局)

根据控制器或方法添加身份验证(非全局):

public class AuthorizationAttribute : AuthorizationFilterAttribute{public override void OnAuthorization(HttpActionContext actionContext){// 如果验证失败,返回未授权的响应if (!IsUserAuthorized(actionContext)){// 如果身份验证失败,返回未授权的响应var content = new Result{success = false,errs = new[] { "服务端拒绝访问:你没有权限" }};actionContext.Response= actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized");actionContext.Response.Content = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");}}private bool IsUserAuthorized(HttpActionContext actionContext){var authorizationHeader = actionContext.Request.Headers.Authorization;if (authorizationHeader != null && authorizationHeader.Scheme == "Bearer" && authorizationHeader.Parameter != null){// 根据实际需求,进行适当的身份验证逻辑// 比较 authorizationHeader.Parameter 和预期的授权参数值return authorizationHeader.Parameter == "111";}return false;}}
public static class WebApiConfig{public static void Register(this HttpSelfHostConfiguration config){// 注册身份验证(全局)//config.MessageHandlers.Add(new BasicAuthorizationHandler());config.Filters.Add(new AuthorizationAttribute());// 配置JSON序列化设置config.RegisterJsonFormatter();// 配置路由config.RegisterRoutes();}private static void RegisterJsonFormatter(this HttpSelfHostConfiguration config){config.Formatters.Clear();config.Formatters.Add(new JsonMediaTypeFormatter());config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();}private static void RegisterRoutes(this HttpSelfHostConfiguration config){//config.MapHttpAttributeRoutes();config.Routes.Clear();config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });}}

然后在控制器中:

 public class ValuesController : ApiController{[HttpGet]public string HelloWorld(){return "Hello World!";}[HttpGet]public ModelTest Test(){var model = new ModelTest();model.Id = Guid.NewGuid().ToString();model.Name = "Test";return model;}[Authorization][HttpGet]public List<ModelTest> Test2(){List<ModelTest> modelTests = new List<ModelTest>();for (int i = 0; i < 3; i++){var model = new ModelTest();model.Id = Guid.NewGuid().ToString();model.Name = "Test";modelTests.Add(model);}return modelTests;}}

全局异常处理:

 public class GlobalExceptionFilter : IExceptionFilter{public bool AllowMultiple => false;public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken){// 在这里实现自定义的异常处理逻辑// 根据实际需求,处理异常并生成适当的响应// 示例:将异常信息记录到日志中LogException(actionExecutedContext.Exception);// 示例:返回带有错误信息的响应var content = new Result{success = false,errs = new[] { "发生了一个错误" }};actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Internal Server Error");actionExecutedContext.Response.Content = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");var tcs = new TaskCompletionSource<object>();tcs.SetResult(null);return tcs.Task;}private void LogException(Exception exception){// 在这里编写将异常信息记录到日志的逻辑}}
public static class WebApiConfig{public static void Register(this HttpSelfHostConfiguration config){// 注册身份验证(全局)//config.MessageHandlers.Add(new BasicAuthorizationHandler());config.Filters.Add(new AuthorizationAttribute());// 注册全局异常过滤器config.Filters.Add(new GlobalExceptionFilter());// 配置JSON序列化设置config.RegisterJsonFormatter();// 配置路由config.RegisterRoutes();}private static void RegisterJsonFormatter(this HttpSelfHostConfiguration config){config.Formatters.Clear();config.Formatters.Add(new JsonMediaTypeFormatter());config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();}private static void RegisterRoutes(this HttpSelfHostConfiguration config){//config.MapHttpAttributeRoutes();config.Routes.Clear();config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });}}

写一个测试接口:

        [HttpGet]public int Test3(){int a = 3;int b = 0;return a / b;}

我们知道有5个Filter,这里只用到了其中的两个,其它自定义实现

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/162904.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Axure插件浏览器一键安装:轻松享受高效工作!

Axure插件对原型设计师很熟悉&#xff0c;但由于Axure插件是在国外开发的&#xff0c;所以在安装Axure插件时不仅需要下载中文包&#xff0c;激活步骤也比较繁琐&#xff0c;有时Axure插件与计算机系统不匹配&#xff0c;Axure插件格式不兼容。本文将详细介绍如何安装Axure插件…

uniapp开发小程序-pc端小程序下载文件

fileName包含文件名后缀名&#xff0c;比如test.png这种格式 api.DownloadTmtFile后端接口返回的是文件的二进制流 值得注意的是&#xff0c;微信开发者工具中是测试不了wx.saveFileToDisk的&#xff0c;需要真机或者体验版测试 handleDownload(fileName) {if (!fileName) retu…

CCFCSP试题编号:201912-2试题名称:回收站选址

这题只要比较坐标的四周&#xff0c;然后计数就可以了。 #include <iostream> using namespace std;int main() {int n;cin >> n;int arr[1005][2] { 0 };int res[5] { 0 };int up 0;int down 0;int left 0;int right 0;int score 0;for (int i 0; i <…

QT 在Windows下实现ping功能(ICMP)

前言 很多时候&#xff0c;我们可能会图省事直接调用系统中的ping命令&#xff0c;但这是很不科学的~ 废话不多说&#xff0c;直接上代码.. .pro文件 在.pro文件末尾添加一行&#xff1a; LIBS -liphlpapi -lws2_32 .h文件 在.h文件中加入&#xff1a; #include <Q…

23款奔驰GLC260L升级原厂360全景影像 高清环绕

本次星骏汇小许介绍的是23款奔驰GLC260L升级原厂360全景影像&#xff0c;上帝视角看清车辆周围环境&#xff0c;更轻松驾驶 升级360全景影像系统共有前后左右4个摄像头&#xff0c;分别在车头&#xff0c;车尾&#xff0c;以及两边反光镜下各一个&#xff0c;分别用来采集车头&…

C# 宏--释义及实例

1.宏-释义 在C#中&#xff0c;宏&#xff08;Macro&#xff09;通常指的是预处理指令&#xff08;Preprocessor Directive&#xff09;&#xff0c;用于在编译时对源代码进行一些宏替换或条件编译的操作。C#中的宏使用预处理器指令#define和#undef来定义和取消定义宏&#xff…

C++string_view简介

1. 简介 C17之后才有string_view&#xff0c;主要为了解决C语言常量字符串在std::string中的拷贝问题。 即readonly的string。 2. 引入 2.1 隐式拷贝问题 将C常量字符串拷贝了一次 #include <iostream> #include <string>int main() {std::string s{ "He…

Modbus RTU、Modbus 库函数

Modbus RTU 与 Modbus TCP 的区别 一般在工业场景中&#xff0c;使用 Modbus RTU 的场景更多一些&#xff0c;Modbus RTU 基于串行协议进行收发数据&#xff0c;包括 RS232/485 等工业总线协议。采用主从问答式&#xff08;master / slave&#xff09;通信。 与 Modbus TCP 不…

基于springboot实现实习管理系统的设计与实现项目【项目源码+论文说明】计算机毕业设计

基于sprinmgboot实现实习管理系统的设计与实现演示 摘要 随着信息化时代的到来&#xff0c;管理系统都趋向于智能化、系统化&#xff0c;实习管理也不例外&#xff0c;但目前国内仍都使用人工管理&#xff0c;市场规模越来越大&#xff0c;同时信息量也越来越庞大&#xff0c;…

普通平衡树

题意&#xff1a;略&#xff0c;题中较清晰。 用二叉查找树来存储数据&#xff0c;为了增加效率&#xff0c;尽量使左子树和右子树的深度差不超过一&#xff0c;这样可以时间控制在logn&#xff0c;效率比较高。 右旋和左旋&#xff0c;目的是为了维护二叉树的操作&#xff0…

Dubbo引入Zookeeper等注册中心简介以及DubboAdmin简要介绍,为后续详解Dubbo各种注册中心做铺垫!

文章目录 一&#xff1a;Dubbo注册中心引言 1&#xff1a;什么是Dubbo的注册中心&#xff1f; 2&#xff1a;注册中心关系图解 3&#xff1a;引入注册中心服务执行流程 4&#xff1a;Dubbo注册中心好处 5&#xff1a;注册中心核心作用 二&#xff1a;注册中心实现方案 …

Springboot+vue的新冠病毒密接者跟踪系统(有报告)。Javaee项目,springboot vue前后端分离项目

演示视频&#xff1a; Springbootvue的新冠病毒密接者跟踪系统(有报告)。Javaee项目&#xff0c;springboot vue前后端分离项目 项目介绍&#xff1a; 本文设计了一个基于Springbootvue的新冠病毒密接者跟踪系统&#xff0c;采用M&#xff08;model&#xff09;V&#xff08;v…

HttpClient实现 get、post、put、delete请求【转】

来自&#xff1a;HttpClient实现 get、post、put、delete请求_httpclient put请求-CSDN博客 目录 HttpClient HttpClient的主要功能 httpclient使用示例主要步骤 Spring Boot 工程结构 HttpClient实现主要代码&#xff1a; GET POST PUT Delete HttpClient HttpCli…

信息系统项目管理师-干系人管理论文提纲

快速导航 1.信息系统项目管理师-项目整合管理 2.信息系统项目管理师-项目范围管理 3.信息系统项目管理师-项目进度管理 4.信息系统项目管理师-项目成本管理 5.信息系统项目管理师-项目质量管理 6.信息系统项目管理师-项目资源管理 7.信息系统项目管理师-项目沟通管理 8.信息系…

景区智慧旅游智能化系统方案:PPT全文58页,附下载

关键词&#xff1a;智慧景区解决方案&#xff0c;智慧文旅解决方案&#xff0c;智慧旅游解决方案&#xff0c;智慧文旅综合运营平台 一、景区智慧旅游智能化系统建设背景 近年来&#xff0c;随着信息技术的快速发展和普及&#xff0c;以及旅游市场的不断扩大和升级&#xff0…

电脑自动删除文件怎么办?如何恢复?

在数字化时代&#xff0c;电脑已经成为人们不可或缺的工具之一。然而&#xff0c;由于各种原因&#xff0c;我们有时会遇到电脑自动删除文件的情况&#xff0c;这给我们的工作和生活带来了很多不便。那么&#xff0c;当电脑自动删除文件时&#xff0c;我们应该如何处理呢&#…

【Python爬虫】8大模块md文档从0到scrapy高手,第8篇:反爬与反反爬和验证码处理

本文主要学习一下关于爬虫的相关前置知识和一些理论性的知识&#xff0c;通过本文我们能够知道什么是爬虫&#xff0c;都有那些分类&#xff0c;爬虫能干什么等&#xff0c;同时还会站在爬虫的角度复习一下http协议。 Python爬虫和Scrapy全套笔记直接地址&#xff1a; 请移步这…

数据结构与算法编程题14

设计一个算法&#xff0c;通过一趟遍历在单链表中确定值最大的结点。 #include <iostream> using namespace std;typedef int Elemtype; #define ERROR 0; #define OK 1;typedef struct LNode {Elemtype data; //结点保存的数据struct LNode* next; //结构体指针…

RedHat NTP时间服务器配置Chrony(所有节点时间跟主节点时间同步)

NTP NTP&#xff08;Network Time Protocol&#xff09;是一种用于在计算机网络中同步时钟的协议。它的主要目的是确保网络中的各个设备具有准确的时间参考&#xff0c;以便协调事件顺序、安全通信和日志记录等应用。它通过分层体系结构、时间同步算法和准确的时间参考源来确保…

Linux设置静态IP

Linux设置静态IP 使用ip addr查看ip&#xff0c;如下所示就是动态IP 1、什么是静态IP&#xff1f; 静态ip就是固定的ip&#xff0c;需要手动设置。静态IP地址&#xff08;又称固定IP地址&#xff09;是长期分配给一台计算机或网络设备使用的 IP 地址。一般来说&#xff0c;一…