【发布时间】:2017-02-02 14:52:20
【问题描述】:
我在 ASP.NET Core 应用程序中有如下 API 控制器。
[Route("api")]
public class UserController : Controller
{
[HttpGet("{userName}/product_info")]
public IActionResult GetProductInfo(string userName)
{
List<ProductInfo> productInfos = _repo.GetProductInfoByUserName(userName);
if (productInfos.Count > 0)
return Ok(productInfos);
else
return BadRequest("Unable to process requrest");
}
}
我可以使用/api/{username}/product_info 调用上面的API。
当用户输入错误的 url 时,我使用 UseStatusCodePagesWithRedirects() 重定向到 404 页面。这里的问题是当我使用错误的 API url 时,例如/api/{username}/product_o。它重定向到 404 页面并返回 200 的状态代码。我将此 API 与 angular.js 一起使用。由于 API 在错误的 URL 上返回 404 页面,状态码为 200,因此永远不会调用 $http 的 then 方法的错误函数,并且在 response.data 中我得到了 404 页面的 HTML。如何在调用错误的 API URL 时返回 404 状态码,并在调用错误的 NON API URL 时返回正常的 404 页面?
下面是我调用错误 API URL 时得到的屏幕截图。
基于@Daboul 的建议和解决方案this link
在startup.cs 的configure 方法中添加以下部分有效。
Func<HttpContext, bool> isApiRequest = (HttpContext context) => context.Request.Path.ToString().Contains("/api/");
app.UseWhen(context => !isApiRequest(context), appBuilder =>
{
appBuilder.UseStatusCodePagesWithRedirects("~/Error/{0}");
});
【问题讨论】:
标签: asp.net-core asp.net-core-mvc asp.net-core-1.0