消息拦截器是一个类,接收 HTTP request并返回 HTTP response,Message handler 继承自抽象类 HttpMessageHandler
可以自定义 MessageHandler,消息拦截器的作用如:

  1. 读取或更改请求头 request headers
  2. 添加 response headers
  3. 在到达 controller 之前,进行参数验证

.Net WebApi消息拦截器之MessageHandler的示例

自定义 Message Handlers

自定义 MessageHandler 需要继承 System.Net.Http.DelegatingHander 并且重载SendAsync方法

Task<HttpResponseMessage> SendAsync(
  HttpRequestMessage request, CancellationToken cancellationToken);

这个方法的一般的处理流程是

  1. 处理请求信息
  2. 调用 base.SendAsync 方法,吧请求发送给内部处理
  3. 内部处理完成之后,返回 response message(这个过程是异步的)
  4. 处理 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);
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
.Net,WebApi,消息拦截器,.Net,WebApi,MessageHandler

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。