Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
              }
       }        
 }
like image 306
Luke Belbina Avatar asked Mar 28 '12 21:03

Luke Belbina


People also ask

What is ActionFilterAttribute in MVC?

The ActionFilterAttribute is the base class for all the attribute filters. It provides the following methods to execute a specific logic after and before controller action's execution: OnActionExecuting(ActionExecutingContext filterContext): Just before the action method is called.

How is exception handling done in MVC?

HandleErrorAttribute. The HandleErrorAttribute is an attribute that can be used to handle exceptions thrown by an action method or a controller. You can use it to display a custom view on a specific exception occurred in an action method or in an entire controller.

Why TempData is used in MVC?

What is TempData and How to Use in MVC? TempData is used to transfer data from the view to the controller, the controller to the view, or from an action method to another action method of the same or a different controller. TempData temporarily saves data and deletes it automatically after a value is recovered.


1 Answers

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.

like image 107
veblock Avatar answered Oct 12 '22 22:10

veblock