How to set HTTP status code from ASP.NET MVC 3?

We use the OpenWeb js libraries on the interface, and they need an average .NET level to send them a specific HTTP header status code when certain types of errors occur. I tried to achieve this by doing the following:

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's kind of like halfway. See screenshot: http status code http://zerogravpro.com/temp/pic.png

Notice that I reached status code 400 in the response header, but I really need 400 in the request header. Instead, I get "200 OK." How can I achieve this?

My url structure for making a call is simple: / Main / TestError / 400

+48
c # asp.net-mvc-3
Aug 24 2018-12-12T00:
source share
2 answers

Extended discussion is being discussed. What is the correct way to send an HTTP 404 response from an ASP.NET MVC action?

What you want to do is set Response.StatusCode instead of adding a header.

 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); } 
+87
Aug 24 2018-12-12T00:
source
โ€” -

If all you want to return is an error code, you can do the following:

 public ActionResult TestError(string id) // id = error code { return new HttpStatusCodeResult(id, "You broke the Internet!"); } 

Link: MSDN article on Mvc.HttpStatusCodeResult .

Otherwise, if you want to return other information, use

 Response.StatusCode = id 

instead

 Response.AddHeader("Status Code", id); 
+56
Aug 24 '12 at 15:39
source



All Articles