Easily returning the HTTP 403 Unauthorized status code from your ASP.NET MVC application

Posted: (EET/GMT+2)

 

Sometimes, you might wish to make certain views or action methods hidden from the user, based on their credentials. ASP.NET MVC already has the built-in AuthorizeAttribute for this purposes, but sometimes, you might need something more fine-grained.

The easily return the HTTP 403 Unauthorized status code from your MVC controller action method, you can use the HttpUnauthorizedResult class.

Here's an example on the usage:

public ActionResult MyActionMethod(string id)
{
    bool canShowView = ...some logic here...;

    if (canShowView)
    {
        return View();
    }
    else
    {
        return new HttpUnauthorizedResult();
    }
}

Note that in case you want to return the HTTP 404 Not Found status code instead, you can use the controller method HttpNotFound like this:

return HttpNotFound();

Hope this helps!