Reputation: 5016
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?
Upvotes: 264
Views: 226885
Reputation: 1364
In project root folder I was deleted bin
folder then rebuild project again. This worked for me:
D:\C# Projects\my_demo_project\WebApplication1\bin
Good luck!
Upvotes: 0
Reputation: 11
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);
}
Upvotes: 1
Reputation: 21440
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
Upvotes: 15
Reputation: 19242
[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 });
}
}
Upvotes: 29
Reputation: 6299
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
}
Upvotes: 459
Reputation: 2660
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;
}
Upvotes: 56
Reputation: 17388
200 is just the normal HTTP header for a successful request. If that's all you need, just have the controller return new EmptyResult();
Upvotes: 58