简体   繁体   中英

Azure does not display custom error message for hosted .net core API

I have the following API endpoint:

[AllowAnonymous]
    [HttpPost("login")]
    public async Task<IActionResult> Authenticate([FromBody] LoginViewModel credentials)
    {
        try
        {
            var result = await _facade.SomeMethodThatFailsAndThrowsCustomCode4001(credentials);
            return Ok(result);
        }
        catch (CustomException cEx)
        {
            return StatusCode(4001, new { Message = cEx.FriendlyMessage ?? "" }); //Message = Our custom user friendly message
        }
    }

When hosted on external server through IIS, these messages were returned perfectly. When hosted on Azure, the messages are not showing, and this is the response received:

{
  "Message": ""
}

I have read about Policies allowed in on-error , but this means I will need to register my .Net Core API with the API management in Azure, and not sure if this is necessary.

What would be required to be configured to allow our custom messages returned through our API hosted in Azure?

You should read RFC doc about HTTP Status Codes .

1xx: Informational - Request received, continuing process

2xx: Success - The action was successfully received, understood, and accepted

3xx: Redirection - Further action must be taken in order to complete the request

4xx: Client Error - The request contains bad syntax or cannot be fulfilled

5xx: Server Error - The server failed to fulfill an apparently valid request

First, after testing, the upper limit of the usable range of StatusCode is 999. When StatusCode >999 , errors will be reported all the time.

在此处输入图像描述

Second, you also can handle custom status code in Startup.cs .

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseHsts();
}
app.UseStatusCodePages(async context =>
{
    if (context.HttpContext.Response.StatusCode == 401)
    {
        await context.HttpContext.Response.WriteAsync("Custom Unauthorized request");
    }
});
//other middlewars

Related Post:

1. How can I return custom error message for error status code 401 in.Net Core?

2. How to return a specific status code and no contents from Controller?

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