How to return custom message if Authorize fails in WebAPI

前端 未结 1 1257
旧时难觅i
旧时难觅i 2020-12-28 14:46

In my WebAPI project, I have number of apis which are decorated with [Authorize] attribute.

[Authorize]
public HttpResponseMessage GetCustomers         


        
相关标签:
1条回答
  • 2020-12-28 15:39

    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.

    0 讨论(0)
提交回复
热议问题