[英]Displaying Custom Server Side Error Message in Angular and .Net Core API
[英]Azure does not display custom error message for hosted .net core API
我有以下 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": ""
}
我已閱讀有關on-error 中允許的策略,但這意味着我需要在 Azure 中使用 API 管理注冊我的.Net Core
API,並且如果不確定是否有必要。
需要進行什么配置以允許我們通過托管在 Azure 中的 API 返回自定義消息?
您應該閱讀有關HTTP Status Codes
的 RFC 文檔。
1xx:信息性 - 收到請求,繼續處理
2xx:成功 - 操作被成功接收、理解和接受
3xx:重定向 - 必須采取進一步行動才能完成請求
4xx:客戶端錯誤 - 請求包含錯誤語法或無法完成
5xx:服務器錯誤 - 服務器未能滿足明顯有效的請求
首先,經測試,StatusCode 的可用范圍上限為 999。當StatusCode >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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.