.Net MVC 与WebApi ActionFilterAttribute 区别

 首先我们来看下 这两个ActionFilterAttribute 的命名空间区别的:

可以看出mvc 引用的是System.Web.Mvc,webapi 引用的是System.Web.Http.Filters ,不知道小伙伴们有看出来别的区别没有,对的,有的 ,虚方法传入类不同,这样导致传入构造与输出构造也将不同了。

这里看下这两个如何拦截的吧,先说下mvc 的:

//OnActionExecuting在被拦截Action前执行
public override void OnActionExecuting(ActionExecutingContext filterContext)
{


 base.OnActionExecuting(filterContext);

 filterContext.HttpContext.Response.Write("Action执行之前"+Message+"<br />");

}

呀。。特码的,你会发现..web api 的玩的不一样,它是继承Http 的

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{

base.OnActionExecuting(actionContext);
}

那如果需要拦截的话,怎么拦截返回呢?

其实很简单,只需要调用http返回状态值,即可拦截不会再往方法内部走了

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{

//此处暂时以401返回,可调整为其它返回
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
//actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);


base.OnActionExecuting(actionContext);
}

原文地址:https://www.cnblogs.com/yiliuyang/p/6062557.html