首页 > Windows开发 > 详细

WebAPI 自定义过滤

时间:2020-11-24 20:24:48      阅读:27      评论:0      收藏:0      [点我收藏+]

 

自定义filter 类过滤

-------------------------------------------------------------------------

public class MyFilter : IAuthorizationFilter
{
  public bool AllowMultiple => true;

  public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>>     continuation)
  {
    IEnumerable<string> name;
    bool v = actionContext.Request.Headers.TryGetValues("username", out name);

    string nm = name.FirstOrDefault();
    if(nm==null)
    {
      return new HttpResponseMessage(HttpStatusCode.Unauthorized);
  }
  else
  {
    return await continuation();
  }

  return new HttpResponseMessage(HttpStatusCode.Unauthorized);

  }
}

 

添加filter 类到配置文件

---------------------------------------------------------------------------------------------------

public static class WebApiConfig
{
  public static void Register(HttpConfiguration config)
  {
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional });
    config.Filters.Add(new MyFilter());
  }
}

 

WebAPI 自定义过滤

原文:https://www.cnblogs.com/bruce1992/p/14032260.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!