257

I am writing an application that is accepting POST data from a third party service.

When this data is POSTed I must return a 200 HTTP Status Code.

How can I do this from my controller?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Paul Brown
  • 4,926
  • 9
  • 32
  • 44

6 Answers6

445

In your controller you'd return an HttpStatusCodeResult like this...

[HttpPost]
public ActionResult SomeMethod(...your method parameters go here...)
{
   // todo: put your processing code here

   //If not using MVC5
   return new HttpStatusCodeResult(200);

   //If using MVC5
   return new HttpStatusCodeResult(HttpStatusCode.OK);  // OK = 200
}
jcolebrand
  • 15,889
  • 12
  • 75
  • 121
Brian Behm
  • 6,129
  • 1
  • 23
  • 30
  • 16
    or rather "return new HttpStatusCodeResult((int)HttpStatusCode.OK);" – dan Dec 18 '12 at 10:10
  • 3
    @dan, that's not needed. There are overloads that take an `int` as well as an `HttpStatusCode`. – MEMark Sep 02 '13 at 20:12
  • 13
    to return a 204 status code do this: return new HttpStatusCodeResult(HttpStatusCode.NoContent); – David Silva Smith Oct 28 '13 at 10:05
  • 2
    @MEMark, I had to cast to make it work. Using .NET 4 & MVC 3 I was not provided with an override that would take an HttpStatusCode. – Shawn South Feb 25 '14 at 01:26
  • 1
    @ShawnSouth, I can't seem to find any information in the docs on what versions contain this overload. http://msdn.microsoft.com/en-us/library/hh413957(v=vs.118).aspx – MEMark Feb 25 '14 at 14:27
  • @MEMark The link you provided is for MVC5, which is where it looks like that overload was introduced. MVC4 doesn't have it: http://msdn.microsoft.com/en-us/library/system.web.mvc.httpnotfoundresult.httpnotfoundresult%28v=vs.108%29.aspx (We're still using MVC3 here.) – Shawn South Feb 25 '14 at 23:37
  • Interestingly, I'm also finding that returning an `HttpStatusCodeResult` (in my case specifically, a `NotFoundResult`) appears to completely bypass the _customError_ settings in the Web.config. The user is instead presented with the ugly IIS error page. – Shawn South Feb 25 '14 at 23:40
  • Correction (I linked to another ActionResult): @MEMark It looks like that overload was introduced in MVC4: http://msdn.microsoft.com/en-us/library/system.web.mvc.httpstatuscoderesult.httpstatuscoderesult%28v=vs.98%29.aspx. – Shawn South Feb 25 '14 at 23:46
  • @ShawnSouth, the link you meant to share is probably this http://msdn.microsoft.com/en-us/library/system.web.mvc.httpstatuscoderesult.httpstatuscoderesult(v=vs.98).aspx I can see know that the left column in my link says MVC 5. I didn't get that it was a breadcrum... I thought that was the main menu. :) (I like the regular MSDN way better, where you for each method get a list of in what framework versions it's available.) – MEMark Feb 26 '14 at 13:28
  • @ShawnSouth, that is the way I would expect it to work. If you tell MVC to return a specific HTTP response, it would be very odd for Web.config to override this. IMHO that setting is only used for when a matching action/page is not found by the runtime. More specifically you could argue that returning a `NotFoundResult` from a controller action is indeed a bit strange. (What is the use case?) – MEMark Feb 26 '14 at 13:30
  • @MEMark The use case is relative to our online Class Schedule (I work for a college), where the route URL denotes quarter/subject. If somebody enters a subject that doesn't exist I want to redirect them to the 404 page. I would expect that if I return a StatusCode of 404, the customErrors configuration would kick in. – Shawn South Feb 26 '14 at 19:10
  • I found and posted the solution to my situation: http://stackoverflow.com/a/22051444/1058872 – Shawn South Feb 26 '14 at 19:36
57

200 is just the normal HTTP header for a successful request. If that's all you need, just have the controller return new EmptyResult();

Kevin Stricker
  • 17,178
  • 5
  • 45
  • 71
  • 5
    You should use `HttpStatusCodeResult(...)` instead as it is much more explicit about what you are trying to achieve. As per the accepted answer. – Ben Jul 22 '19 at 09:39
54

You can simply set the status code of the response to 200 like the following

public ActionResult SomeMethod(parameters...)
{
   //others code here
   ...      
   Response.StatusCode = 200;
   return YourObject;  
}
Jack
  • 2,600
  • 23
  • 29
29
    [HttpPost]
    public JsonResult ContactAdd(ContactViewModel contactViewModel)
    {
        if (ModelState.IsValid)
        {
            var job = new Job { Contact = new Contact() };

            Mapper.Map(contactViewModel, job);
            Mapper.Map(contactViewModel, job.Contact);

            _db.Jobs.Add(job);

            _db.SaveChanges();

            //you do not even need this line of code,200 is the default for ASP.NET MVC as long as no exceptions were thrown
            //Response.StatusCode = (int)HttpStatusCode.OK;

            return Json(new { jobId = job.JobId });
        }
        else
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(new { jobId = -1 });
        }
    }
Brian Ogden
  • 18,439
  • 10
  • 97
  • 176
13

The way to do this in .NET Core is (at the time of writing) as follows:

public async Task<IActionResult> YourAction(YourModel model)
{
    if (ModelState.IsValid)
    {
        return StatusCode(200);
    }

    return StatusCode(400);
}

The StatusCode method returns a type of StatusCodeResult which implements IActionResult and can thus be used as a return type of your action.

As a refactor, you could improve readability by using a cast of the HTTP status codes enum like:

return StatusCode((int)HttpStatusCode.OK);

Furthermore, you could also use some of the built in result types. For example:

return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON

Ref. StatusCodeResult - https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1

user1477388
  • 20,790
  • 32
  • 144
  • 264
0

If you have a custom object that needs to be returned within the Status 200 response, you can pass a custom object as an OkObjectResult:

public IActionResult Get()
    {
        CustomObject customObject = new CustomObject();

        return Ok(customObject);
    }