nicetomeetyouASPWebAPI全局权限和全局异常处理
在开发中,我使⽤json格式序列化,所以将默认的xml序列化移除
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// ...
var json = config.Formatters.JsonFormatter;
// 解决json序列化时的循环引⽤问题
uge
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// 移除XML序列化器
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
全局权限验证过滤器
新建⼀个类继承⾃AuthorizationFilterAttribute,它有⼀个虚⽅法OnAuthorization,在权限验证的时候调⽤,重写这个⽅法来验证权限。[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class WebApiAuthAttribute : AuthorizationFilterAttribute
秘密韩语{
public override void OnAuthorization(HttpActionContext actionContext)
{
// 这是⼀个基本例⼦,使⽤的ASP Forms ⾝份验证
var context = HttpContext.Current;
if (context.Ur.Identity.IsAuthenticated == fal)concern
{roundrobin
PreUnauthorized(actionContext);
return;
}
}
private void PreUnauthorized(HttpActionContext actionContext)
{
glamour girl// 如果⽤户没有登录,则返回⼀个通⽤的错误Model
actionContext.Respon = actionContext.Request.CreateRespon(
HttpStatusCode.OK,
new AjaxModel
{
StatusCode = AjaxStatusCode.Unauthorized,
Message = "该操作需要⽤户登录"
});ammy
}
英翻中在线翻译}
最后只需要在WebApiConfig⾥⾯添加⼀个过滤器
config.Filters.Add(new WebApiAuthAttribute());
现在每⼀个请求都会验证权限respectful
全局异常过滤器
新建⼀个类继承⾃ExceptionFilterAttribute,同样有⼀个虚⽅法OnException,重写这个⽅法来处理异常。
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
Logger.Error(actionExecutedContext.Exception);
actionExecutedContext.Respon = actionExecutedContext.Request.CreateRespon(
HttpStatusCode.OK,
new AjaxModel
{
yes or no下载
StatusCode = AjaxStatusCode.InternalServerError,
Message = actionExecutedContext.Exception.Message
});
}
最后只需要在WebApiConfig⾥⾯添加⼀个过滤器
config.Filters.Add(new WebApiErrorHandleAttribute());