导航

webapi自定义Filter

Posted on 2018-06-05 00:44  颍川小哥  阅读(265)  评论(0编辑  收藏  举报

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

public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
IEnumerable<string> UserNames;
if (!actionContext.Request.Headers.TryGetValues("UserName", out UserNames))
{
return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
string username = UserNames.First();
if (username=="admin")
{
return await continuation();
}
else
{
return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}

}
}

 

 

 

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

 

 

还有ActionFilter  ExceptionFilter

 

 

 

 

 

apiResult 用法

 

 

public class ApiResult<T>
{
public int Code { get; set; }
public string Message { get; set; }
public T ReturnValue { get; set; }
}

 

public ApiResult<string> Get(int id)
{
if (id<0)
{
return new ApiResult<string> { Code = 1, Message = "年龄太小" };
}
else if(id>100)
{
return new ApiResult<string> { Code = 2, Message = "年龄太da" };
}
else
{
return new ApiResult<string> { Code = 0, ReturnValue="Hellp" };
}
}