How to return custom message if Authorize fails in WebAPI

[亡魂溺海] 提交于 2019-12-02 20:38:44

There are different ways to do this but one of the best way could be custom authorization attributes.You just need to inherit the AuthorizeAttribute and override HandleUnauthorizedRequest() method of it.

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 like(CustomAuthorization should be used in-place of Authorize)

    [CustomAuthorization]       
    public IHttpActionResult Get()
    {
        return Ok();
    }

Otherwise you can also catch the status code in client side and display the custom message of your choice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!