How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

前端 未结 5 1504
刺人心
刺人心 2020-12-12 11:48

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

5条回答
  •  生来不讨喜
    2020-12-12 12:14

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

    public async Task 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://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1

提交回复
热议问题