There are various ways to do this, but one of the best ways might be custom authorization attributes. You just need to inherit the AuthorizeAttribute
method and override HandleUnauthorizedRequest()
.
public class CustomAuthorization : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent("You are unauthorized to access this resource") }; } }
and use this as ( CustomAuthorization
should be used instead of Authorize
)
[CustomAuthorization] public IHttpActionResult Get() { return Ok(); }
Otherwise, you can also catch the status code on the client side and display a custom message of your choice.
source share