自定义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());
}
}