0

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?

monstertjie_za
  • 7,277
  • 8
  • 42
  • 73

1 Answers1

1

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.

enter image description here

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?

Jason Pan
  • 15,263
  • 1
  • 14
  • 29