欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-29 13:25:47
消息拦截器是一个类,接收 http request并返回 http response,message handler 继承自抽象类 httpmessagehandler...

消息拦截器是一个类,接收 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);
    }
  }
}

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