您的位置:首页 > 其它

MVC及Web API添加身份验证及错误处理的过滤器

2016-06-14 16:38 555 查看
MVC及Web API添加身份验证及错误处理的过滤器
先说身份验证的问题。无论是mvc还是api都有一个安全性的问题,未通过身份验证的人能不能访问的问题。我们新一个空项目时,默认是没有身份验证的,除非你在控制器类或者方法上面加上Authorize属性才会需要身份验证。但是我的控制器有那么多,我都要给它加上属性,多麻烦,所以我们就想到过滤器了。过滤器中加上后,控制器都不用加就相当于有这个属性了。

Mvc的就直接在FilterConfig类的RegisterGlobalFilters方法中添加以下代码即可

filters.Add(new System.Web.Mvc.AuthorizeAttribute());


Web Api的过滤器没有单独一个配置类,可以写在WebApiConfig类的Register中

config.Filters.Add(new System.Web.Http.AuthorizeAttribute());


Mvc错误处理默认有添加HandleErrorAttribute默认的过滤器,但是我们有可能要捕捉这个错误并记录系统日志那么这个过滤器就不够用了,所以我们要自定义Mvc及Web Api各自的错误处理类,下面贴出我的错误处理,MvcHandleErrorAttribute

using System.Web;

using System.Web.Mvc;

using log4net;

namespace Zephyr.Web

{

public class MvcHandleErrorAttribute : HandleErrorAttribute

{

public override void OnException(ExceptionContext filterContext)

{

ILog log = LogManager.GetLogger(filterContext.RequestContext.HttpContext.Request.Url.LocalPath);

log.Error(filterContext.Exception);

base.OnException(filterContext);

}

}

}


Web API的错误处理

using System.Net;

using System.Net.Http;

using System.Web;

using System.Web.Http.Filters;

using log4net;

namespace Zephyr.Web

{

public class WebApiExceptionFilter : ExceptionFilterAttribute

{

public override void OnException(HttpActionExecutedContext context)

{

ILog log = LogManager.GetLogger(HttpContext.Current.Request.Url.LocalPath);

log.Error(context.Exception);

var message = context.Exception.Message;

if (context.Exception.InnerException != null)

message = context.Exception.InnerException.Message;

context.Response = new HttpResponseMessage() { Content = new StringContent(message) };

base.OnException(context);

}

}

}


然后分别注册到过滤器中,在FilterConfig类的RegisterGlobalFilters方法中

filters.Add(new MvcHandleErrorAttribute());


在WebApiConfig类的Register中

config.Filters.Add(new WebApiExceptionFilter());


这样过滤器就定义好了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: