【问题标题】:Azure does not display custom error message for hosted .net core APIAzure 不显示托管 .net 核心 API 的自定义错误消息
【发布时间】:2021-05-01 03:11:00
【问题描述】:

我有以下 API 端点:

[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
        }
    }

当通过 IIS 托管在外部服务器上时,这些消息可以完美返回。在 Azure 上托管时,消息未显示,这是收到的响应:

{
  "Message": ""
}

我已阅读有关 Policies allowed in on-error 的信息,但这意味着我需要在 Azure 中的 API 管理中注册我的 .Net Core API,但不确定这是否有必要。

需要进行哪些配置才能允许通过托管在 Azure 中的 API 返回自定义消息?

【问题讨论】:

  • 返回时状态码是 4001 吗?如果您对消息进行硬编码,例如 new { Message = "My test Message" },会发生什么?
  • 当您说“托管在 Azure 上”时,您能否澄清一下您是否指的是 Azure 应用服务?
  • @tnk479 没错
  • 您想使用 4001 作为有效的状态码吗?
  • @tnk479 是的,这就是我想做的事

标签: c# azure api asp.net-core


【解决方案1】:

你应该read RFC doc about HTTP Status Codes

1xx:信息性 - 收到请求,继续处理

2xx:成功 - 操作已成功接收、理解和接受

3xx:重定向 - 必须采取进一步措施才能完成请求

4xx:客户端错误 - 请求包含错误语法或无法完成

5xx:服务器错误 - 服务器未能满足明显有效的请求

首先,经测试,StatusCode的可用范围上限为999。StatusCode &gt;999时,会一直报错。

其次,您还可以在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

相关帖子:

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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多