iraSenthil
iraSenthil

Reputation: 11577

How to return status code 401 along some additional data?

I am trying to write a custom Authorize attribute to authorize some of the API endpoints and MVC actions. Following this StackOverflow answer, I wrote a custom attribute. I am using UnauthorizedResult to return 401.

  1. For Web API, How can I return status codes 401 or 403 along with some additional message as JSON payload?
  2. For MVC Actions that return HTML, How can I return status codes 401 or 403 and redirect to different URL?
  3. How can I check if the request is WebAPI or MVC action?

Upvotes: 2

Views: 8033

Answers (2)

A more modern response that applies to ASP.NET Core at least would be

public async Task<IActionResult> CtrlAction()
{
    ...
    var result = // whatever object you want
    return StatusCode((int) HttpStatusCode.Unauthorized, result);
}

Upvotes: 1

Ivan Leonenko
Ivan Leonenko

Reputation: 2383

Answering your first question, this is how overridden method of authorization attribute may look like. Error message will be status message and content is in response body.

public override Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
{
    string errorMessage = "User has no enough permissions to perform requested operation.";

    var httpContent = new StringContent("{ \"some\": \"json\"}", Encoding.UTF8, "application/json");

    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
    {
        ReasonPhrase = errorMessage,
        Content = httpContent
    };

    return Task.FromResult<object>(null);
}

From MVC action you can return status code like this return StatusCode(418); or using dedicated method like return Unauthorized();. To redirect you can use RedirectToAction or context.Response.Redirect

Upvotes: 1

Related Questions