WebAPI 自定义过滤

 

自定义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 自定义过滤

上一篇:AnyCAD C#开发-创建2D的Text,显示在屏幕空间TextNode


下一篇:delphi xe 10分组按钮CategoryButtons 折叠按钮