MVC及Web API添加身份验证及错误处理的过滤器
2016-06-14 16:38
555 查看
MVC及Web API添加身份验证及错误处理的过滤器
先说身份验证的问题。无论是mvc还是api都有一个安全性的问题,未通过身份验证的人能不能访问的问题。我们新一个空项目时,默认是没有身份验证的,除非你在控制器类或者方法上面加上Authorize属性才会需要身份验证。但是我的控制器有那么多,我都要给它加上属性,多麻烦,所以我们就想到过滤器了。过滤器中加上后,控制器都不用加就相当于有这个属性了。
Mvc的就直接在FilterConfig类的RegisterGlobalFilters方法中添加以下代码即可
Web Api的过滤器没有单独一个配置类,可以写在WebApiConfig类的Register中
Mvc错误处理默认有添加HandleErrorAttribute默认的过滤器,但是我们有可能要捕捉这个错误并记录系统日志那么这个过滤器就不够用了,所以我们要自定义Mvc及Web Api各自的错误处理类,下面贴出我的错误处理,MvcHandleErrorAttribute
Web API的错误处理
然后分别注册到过滤器中,在FilterConfig类的RegisterGlobalFilters方法中
在WebApiConfig类的Register中
这样过滤器就定义好了。
先说身份验证的问题。无论是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());
这样过滤器就定义好了。
相关文章推荐
- AFNetwoking 3.1 https请求相关
- poj 1017贪心-装箱
- 在32位Windows上扩展虚拟内存(Labview)
- 咏南开发框架调用存储过程演示
- 删除数组中指定的某个元素
- 选中一行并且选中该行的radio
- 图情期刊要求2015(A,B,C类)
- php代码效率测试
- 使用PreTranslateMessage(MSG* pMsg)截获键盘数字键
- was密码遗忘的解决方案
- 几何学
- cocoapods中的pod file介绍
- 体外诊断(POCT)之系统配置文件修改
- cloud 数据库操作方法
- 【干货】”首个“ .NET Core 验证码组件
- js 返回上一页
- 反射工具类、流操作工具类、文件操作工具类
- JavaScript实现全选 反选 全不选
- 实习杂记(23):ant有关的知识点
- 由eclipse工程创建一个Android studio 工程