亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Web api 和 Mvc Razor 中的 Dotnet Core 錯誤處理

Web api 和 Mvc Razor 中的 Dotnet Core 錯誤處理

C#
大話西游666 2022-06-18 17:27:15
在我的 Web 應用程序中,我有 Web API 和普通的 MVC,我為 httpResponse 創建了一個擴展 public static void ShowApplicationError(this HttpResponse response, string exceptionMessage,string innerException)    {        var result = JsonConvert.SerializeObject(new { error = exceptionMessage ,detail=innerException });        response.HttpContext.Response.WriteAsync(result);    }并在 startup.cs 中用于異常處理。app.UseExceptionHandler(builder =>            {                builder.Run(async context =>                {                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;                    var error = context.Features.Get<IExceptionHandlerFeature>();                    if (error != null)                    {                        context.Response.ShowApplicationError(error.Error.Message, error.Error.InnerException.Message);                    }                });            });像這樣。它對兩者都很好。我想區分每個請求的錯誤。我不想顯示 mvc 的 json 錯誤結束我該怎么做。
查看完整描述

3 回答

?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

這種情況的最佳解決方案是更好地分離您的關注點。使您的 api 成為與您的 MVC 應用程序分開的 csproj。它還將為您提供以后部署的靈活性。如果這是現有代碼而不是新代碼,我會游說將其重構為單獨的 api 項目。



查看完整回答
反對 回復 2022-06-18
?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

您無法直接將內部服務器錯誤與 MVC 或 Web api 區分開來Error.Message。對于MVCand Web api,它們都繼承自Controlleror ControllerBase。


一般來說,我們通過添加api到 web api 的路由路徑來區分它們。我建議您通過不帶 api 路由的 mvc 和帶 api 路由的 web api 來設計您的項目。然后檢查路徑ExceptionHandlerFeature.Path。


app.UseExceptionHandler(builder =>

{

    builder.Run(async context =>

    {

        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        var error = context.Features.Get<IExceptionHandlerFeature>();

        var error1 = context.Features.Get<IExceptionHandlerFeature>() as ExceptionHandlerFeature;

        var error2 = context.Features.Get<IExceptionHandlerPathFeature>();

        var requestPath = error2.Path;

        if (error != null)

        {

            context.Response.ShowApplicationError(error.Error.Message, error.Error.InnerException.Message);

        }

    });

});


查看完整回答
反對 回復 2022-06-18
?
青春有我

TA貢獻1784條經驗 獲得超8個贊

HttpRequest 中的 ContentType 和 Accept Header 區分輸出類型,這在您的情況下就足夠了。


您可以使用 Accept Header 進行檢查。


if (context.Request.Headers["Accept"] == "application/json" || context.Request.Headers["Accept"] == "application/xml")

{

    //Api Request

}

else

{

    //other request.

}


查看完整回答
反對 回復 2022-06-18
  • 3 回答
  • 0 關注
  • 151 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號