简体   繁体   中英

Correct way to raise an exception in an ASP.NET MVC 4 ActionFilterAttribute

Note that this is for an ApiController in MVC 4 although I think it shouldn't change anything.

 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.
              }
       }        
 }

You can set the result property of the HttpActionContext :

public override void OnActionExecuting(HttpActionContext actionContext)
{
    if (checkVerified())
    {
        actionContext.Response = 
            new HttpResponseMessage(HttpStatusCode.Unauthorized);
    }
}

you may probably just throw:

throw new HttpResponseException(HttpStatusCode.Unauthorized);

but I haven't checked that one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM