C# 如何从 ASP.NET MVC 3 设置 HTTP 状态代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12112361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set HTTP status code from ASP.NET MVC 3?
提问by HerrimanCoder
We're using OpenWeb js libraries on the frontend, and they have a need for the .NET middle tier to send them a specific HTTP header status code when certain types of errors occur. I tried to achieve that by doing this:
我们在前端使用 OpenWeb js 库,他们需要 .NET 中间层在发生某些类型的错误时向他们发送特定的 HTTP 标头状态代码。我试图通过这样做来实现这一目标:
public ActionResult TestError(string id) // id = error code
{
Request.Headers.Add("Status Code", id);
Response.AddHeader("Status Code", id);
var error = new Error();
error.ErrorID = 123;
error.Level = 2;
error.Message = "You broke the Internet!";
return Json(error, JsonRequestBehavior.AllowGet);
}
It kind of halfway worked. See screenshot: http status code http://zerogravpro.com/temp/pic.png
它有点成功了。看截图: http 状态码 http://zerogravpro.com/temp/pic.png
Notice I achieved the Status Code of 400 in the Response Header, but I really need the 400 in the Request Header. Instead, I get "200 OK". How can I achieve this?
请注意,我在响应头中获得了 400 的状态代码,但我确实需要请求头中的 400。相反,我得到“200 OK”。我怎样才能做到这一点?
My URL structure for making the call is simple: /Main/TestError/400
我的调用 URL 结构很简单:/Main/TestError/400
采纳答案by Steve Czetty
There is extended discussion at What is the proper way to send an HTTP 404 response from an ASP.NET MVC action?
有一个在广泛讨论什么是到从ASP.NET MVC操作的HTTP 404响应的正确方法?
What you want to do is set Response.StatusCodeinstead of adding a Header.
您要做的是设置Response.StatusCode而不是添加标题。
public ActionResult TestError(string id) // id = error code
{
Response.StatusCode = 400; // Replace .AddHeader
var error = new Error(); // Create class Error() w/ prop
error.ErrorID = 123;
error.Level = 2;
error.Message = "You broke the Internet!";
return Json(error, JsonRequestBehavior.AllowGet);
}
回答by Nick Jones
If all you want to return is the error code, you could do the following:
如果您只想返回错误代码,您可以执行以下操作:
public ActionResult TestError(string id) // id = error code
{
return new HttpStatusCodeResult(id, "You broke the Internet!");
}
Reference: MSDN article on Mvc.HttpStatusCodeResult.
参考:关于 Mvc.HttpStatusCodeResult 的 MSDN 文章。
Otherwise, if you want to return other information use
否则,如果您想返回其他信息,请使用
Response.StatusCode = id
instead of
代替
Response.AddHeader("Status Code", id);
回答by Ludo.C
If you can't get your json result into your view, try to add this :
如果您无法将 json 结果显示在您的视图中,请尝试添加以下内容:
Response.TrySkipIisCustomErrors = true;
Before this :
在这之前 :
Response.StatusCode = 400;
More details on this post : https://stackoverflow.com/a/37313866/9223103
关于这篇文章的更多细节:https: //stackoverflow.com/a/37313866/9223103

