.Net WebApi消息拦截器之MessageHandler的示例
消息拦截器是一个类,接收 HTTP request并返回 HTTP response,Message handler 继承自抽象类 HttpMessageHandler
可以自定义 MessageHandler,消息拦截器的作用如:
- 读取或更改请求头 request headers
- 添加 response headers
- 在到达 controller 之前,进行参数验证
自定义 Message Handlers
自定义 MessageHandler
需要继承 System.Net.Http.DelegatingHander
并且重载SendAsync方法
Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken);
这个方法的一般的处理流程是
- 处理请求信息
- 调用
base.SendAsync
方法,吧请求发送给内部处理 - 内部处理完成之后,返回
response message
(这个过程是异步的) - 处理
response
之后,返回给调用者
public class MessageHandler1 : DelegatingHandler { protected async override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { Debug.WriteLine("Process request"); // Call the inner handler. var response = await base.SendAsync(request, cancellationToken); Debug.WriteLine("Process response"); return response; } }
消息拦截器生效
在 WebApiConfig
中注册相关
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MessageHandlers.Add(new MessageHandler1()); config.MessageHandlers.Add(new MessageHandler2()); // Other code not shown... } }
https 请求拦截器
要求所有的请求都必须是https的请求,可以自定义一个https的拦截器,如果是https请求,就继续处理,否则就返回相关的提示信息
public class RequireHttpsHandler : DelegatingHandler { public RequireHttpsHandler(int httpsPort) { _httpsPort = httpsPort; } public RequireHttpsHandler() : this(443) { } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { //判断是否是 https 请求 if (request.RequestUri.Scheme == Uri.UriSchemeHttps) return base.SendAsync(request, cancellationToken); var response = CreateResponse(request); var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(response); return tcs.Task; } private HttpResponseMessage CreateResponse(HttpRequestMessage request) { HttpResponseMessage response; var uri = new UriBuilder(request.RequestUri); uri.Scheme = Uri.UriSchemeHttps; uri.Port = _httpsPort; var body = string.Format("HTTPS is required<br/>The resource can be found at <a href=\"{0}\">{0}</a>.", uri.Uri.AbsoluteUri); if (request.Method.Equals(HttpMethod.Get) || request.Method.Equals(HttpMethod.Head)) { response = request.CreateResponse(HttpStatusCode.Found); response.Headers.Location = uri.Uri; if (request.Method.Equals(HttpMethod.Get)) response.Content = new StringContent(body, Encoding.UTF8, "text/html"); } else { response = request.CreateResponse(HttpStatusCode.NotFound); response.Content = new StringContent(body, Encoding.UTF8, "text/html"); } return response; } }
Enable CORS 拦截器
public class SimpleCorsHandler : DelegatingHandler { private const string origin = "Origin"; private const string accessControlRequestMethod = "Access-Control-Request-Method"; private const string accessControlRequestHeaders = "Access-Control-Request-Headers"; private const string accessControlAllowOrigin = "Access-Control-Allow-Origin"; private const string accessControlAllowMethods = "Access-Control-Allow-Methods"; private const string accessControlAllowHeaders = "Access-Control-Allow-Headers"; protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var isCorsRequest = request.Headers.Contains(origin); var isPreflightRequest = request.Method == HttpMethod.Options; if (isCorsRequest) { if (isPreflightRequest) { return Task.Factory.StartNew(() => { var response = new HttpResponseMessage(HttpStatusCode.OK); response.Headers.Add(accessControlAllowOrigin, request.Headers.GetValues(origin).First()); var currentAccessControlRequestMethod = request.Headers.GetValues(accessControlRequestMethod). FirstOrDefault(); if (currentAccessControlRequestMethod != null) { response.Headers.Add(accessControlAllowMethods, currentAccessControlRequestMethod); } var requestedHeaders = string.Join(", ", request.Headers.GetValues(accessControlRequestHeaders)); if (!string.IsNullOrEmpty(requestedHeaders)) { response.Headers.Add(accessControlAllowHeaders, requestedHeaders); } return response; }, cancellationToken); } else { return base.SendAsync(request, cancellationToken).ContinueWith(t => { var resp = t.Result; resp.Headers.Add( accessControlAllowOrigin, request.Headers.GetValues(origin).First()); return resp; }); } } else { return base.SendAsync(request, cancellationToken); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
- 详解ASP.NET Core WebApi 返回统一格式参数
- asp.net core webapi项目配置全局路由的方法示例
- ASP.NET WebAPI连接数据库的方法
- .Net Core2.1 WebAPI新增Swagger插件详解
- .Net Web Api中利用FluentValidate进行参数验证的方法
- ASP.net WebAPI跨域调用问题的解决方法
- asp.net core webapi 服务端配置跨域的实例
- ASP.NET Core 2.0 WebApi全局配置及日志实例
- asp.net core 2.0 webapi集成signalr(实例讲解)
- 详解.net core webapi 前后端开发分离后的配置和部署
相关文章
asp.net开发sql server转换成oracle的方法详解
这篇文章主要给大家介绍了关于asp.net开发中sql server转换成oracle的相关资料,文中通过示例代码和图文将实现的步骤一步步介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧。2017-08-08asp.net用url重写URLReWriter实现任意二级域名 新
最近有个朋友要做url重写的东西,我帮他弄了弄,回头看当年自己写的那个文章,当时以为自己写的很容易理解.但现在再看却觉得写的不好.而今天百度了一下urlrewriter发现我这个文章竟然排第二.为了方便更多朋友,我再写点东西补充下.2009-11-11
最新评论