简体   繁体   中英

Creating Custom Error 401 Response in Controller Web API

Hi I'm stuck on a roadblock regarding on how to create a custom Error 401 Message, I'm reading some of the tutorials on how to create custom error response in C#,When I see some of the codes most of them are not working and some are quite messy to look and understand.

Here's my code

Notice that I Used [Authorize] attribute to return if the function that I'm using are authorized.

[Authorize]     
        [HttpGet]
        public HttpResponseMessage gethistogram(string entity_name, string kpi_name, string chart_type, int unix_start, int unix_end, string language)
        {

            var result = _definitionRepository.histogram(entity_name,kpi_name,chart_type,unix_start,unix_end,language);
            //if (result == null)
            //{
            //    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, " Entity Name? Chart Type? KPI Name?, Language? Unix Start? or Unix End?");
            //}
            //return Request.CreateResponse(HttpStatusCode.OK, result);
            if (chart_type == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid chart Type to access data");
            }
            if (kpi_name == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid KPI name to access data");
            }
            if (entity_name == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid Entity name to access data");
            }
            if (kpi_name == null && chart_type == null && entity_name == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Required parameters missing to access data");
            }
            return Request.CreateResponse(HttpStatusCode.OK, result);

        }

I want to change the Default Error Response from

{
    "Message": "Authorization has been denied for this request."
}

into

{
    "Message": "This request is unauthorized"
}

Here is my Repository for Checking

public List<Root> histogram(string entity_name, string kpi_name , string chart_type ,int unix_start, int unix_end, string language)
{
    var all = _db
        .kpi_definition
        //.Include("KPI")
        .Where(dl => entity_name == dl.entity_name && kpi_name == dl.kpi_name && chart_type == dl.chart_type && unix_start == dl.unix_start && unix_end == dl.unix_end && language == dl.language)
        .Select(dl => new Root
        {
            chart_type = new List<Chart>
            {
               new Chart { entity_name = dl.entity_name ,
                           entity_display_name = dl.entity_display_name,
                           kpi = new List<KPI>
                           {
                              new KPI {
                                       kpi_name = dl.kpi_name,
                                       kpi_display_name = dl.kpi_display_name,
                                       required = new List<Required>
                                       {
                                           new Required
                                           {
                                               //kpi_required = dl.kpi_required
                                           }
                                       },
                                       optional = new List<Optional>
                                       {
                                           new Optional
                                           {
                                               //kpi_optional = dl.kpi_optional
                                           }
                                       },
                                       objects = new List<Objects>
                                       {
                                           new Objects
                                           {
                                               field_name = new List<FieldName>
                                               {
                                                   new FieldName
                                                   {
                                                    entity_display_name = dl.entity_display_name,
                                                    type = "Select or Text",
                                                    @default = "default value(already selected)",
                                                    list = "",
                                                    ID = dl.ID
                                                   }
                                               }

                                           }
                                       }
                                      }
                           }
                         }
            }
        }).ToList();
    return all;
}

I think you can create a custom authorization filter that sets the response to 401 along with the custom message. Here is the link ' How to return custom message if Authorize fails in WebAPI ', which I believe is what you are trying to achieve. So, in a nutshell, we need to create a class, lets say CustomAuthorize inheriting AuthorizeAttribute

public class CustomAuthorize : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext 
       actionContext)
    {
        actionContext.Response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.Forbidden,
            Content = new StringContent("This request is unauthorized")
        };
    }
}

Then we can use this attribute instead of Authorize filter on top of gethistogram method like this

    [CustomAuthorize]     
    [HttpGet]
    public HttpResponseMessage gethistogram(string entity_name, 
        string kpi_name, string chart_type, int unix_start, int 
        unix_end, string language)
    {

        var result = _definitionRepository.histogram(entity_name,kpi_name,chart_type,unix_start,unix_end,language);
        //if (result == null)
        //{
        //    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, " Entity Name? Chart Type? KPI Name?, Language? Unix Start? or Unix End?");
        //}
        //return Request.CreateResponse(HttpStatusCode.OK, result);
        if (chart_type == null)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid chart Type to access data");
        }
        if (kpi_name == null)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid KPI name to access data");
        }
        if (entity_name == null)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid Entity name to access data");
        }
        if (kpi_name == null && chart_type == null && entity_name == null)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Required parameters missing to access data");
        }
        return Request.CreateResponse(HttpStatusCode.OK, result);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM