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.
}
}
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With