3 回答

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

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);
}
});
});

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.
}
- 3 回答
- 0 關注
- 151 瀏覽
添加回答
舉報