我最近一直坚持这一点,无法弄清楚为什么会这样。
我在.Net Core中使用MVC控制器返回NotFound()“404”响应。 但是,客户端(使用angular)如果我在console.log中响应,则显示此...
状态:200个
状态文本: “OK”
有没有理由为什么返回NotFound()会返回错误代码200而不是预期的404?
这是我的控制器GET。
// GET: api/cause/cause-name
[HttpGet("{name}")]
[AllowAnonymous]
public IActionResult GetCauseByName(string name)
{
var input = _service.GetCauseByName(name);
if (input == null)
{
return NotFound();
}
else
{
return Ok(input);
}
}
任何帮助将不胜感激!谢谢!
要清楚,对于此实例,假设输入为空。我正在测试的是它击中NotFound()而不是返回OK(输入)。断点已经设置,它确实命中了NotFound(),但仍然返回200的响应代码。
标题 -
GET /cause/dsdasdas
HTTP/1.1
Host: localhost:48373
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8 Accept-Encoding: gzip, deflate, sdch, br Accept-Language: en-US,en;q=0.8
HTTP/1.1
200 OK
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip Vary:
Accept-Encoding Server: Kestrel X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcaXR0ZW1wNVxEZXNrdG9wXFByb2plY3RGdW5kQXBwXHNyY1xQcm9qZWN0RnVuZFxjYXVzZVxkc2Rhc2Rhcw==?= X-Powered-By: ASP.NET Date: Thu, 25 May 2017 14:51:29 GMT –
POSTMAN HEADERS
Content-Encoding →gzip
Content-Type →text/html; charset=utf-8
Date →Thu, 25 May 2017 15:18:31 GMT
Server →Kestrel
Transfer-Encoding →chunked
Vary →Accept-Encoding
X-Powered-By →ASP.NET
X-SourceFiles →=?UTF-8?B?QzpcVXNlcnNcaXR0ZW1wNVxEZXNrdG9wXFByb2plY3RGdW5kQXBwXHNyY1xQcm9qZWN0RnVuZFxjYXVzZVxkc2Rhc2Rhcw==?=
答案 0 :(得分:0)
我问了类似的问题并收到了某种答案... NotFound() doesn't seem to work as expected
解决方案Redirect("~/404.html");
返回200。
但是,还有另一种方式。
// Wherever you want to return your standard 404 page
return Redirect("Home/StatusCode?code=404");
public class HomeController : Controller
{
// This method allows for other status codes as well
public IActionResult StatusCode(int? code)
{
// This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
if (code.HasValue)
{
// here is the trick
this.HttpContext.Response.StatusCode = code.Value;
}
//return a static file.
try
{
return File("~/" + code + ".html", "text/html");
}
catch (FileNotFoundException)
{
return Redirect("Home/StatusCode?code=404");
}
}
}
这确实返回404。