在ASP.NET MVC 4 ActionFilterAttribute中引发异常的正确方法

时间:2012-03-28 21:46:54

标签: c# asp.net-mvc-3

请注意,这是针对MVC 4中的ApiController,尽管我认为它不会改变任何内容。

 public class OAuthFilter : System.Web.Http.ActionFilterAttribute
 {
       public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
       {
              if (checkVerified())
              {
                   // How to raise a 401 or some other type of exception.
              }
       }        
 }

1 个答案:

答案 0 :(得分:13)

您可以设置HttpActionContext的结果属性:

public override void OnActionExecuting(HttpActionContext actionContext)
{
    if (checkVerified())
    {
        actionContext.Response = 
            new HttpResponseMessage(HttpStatusCode.Unauthorized);
    }
}
你可能会抛出:

throw new HttpResponseException(HttpStatusCode.Unauthorized);

但我没有检查过那个。

相关问题