Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the HttpConflict in MVC6?

I'm a C++ guy with no "web stuff" experience, but my supervisors want me to go learn the ways of "ASP.NET MVC 6", because it's the latest snazzy thing.

I managed to get a hold of at least one tutorial, but I see no reference and no documentation anywhere. Where do I look up what classes and methods there are?

My current problem is that I am trying to figure out how to return a Http status of 409 from my Create method in my controller. I don't see a HttpConflict method. What do I call?

like image 335
Christopher Pisz Avatar asked Dec 14 '22 11:12

Christopher Pisz


2 Answers

With ASP.NET Core 1.0 you can use the StatusCode(int statusCode) method available on any Controller.

[HttpPost]
public IActionResult Create([FromBody] Widget item)
{
  // ...

  // using the HttpStatusCode enum keeps it a little more readable
  return StatusCode((int) HttpStatusCode.Conflict); 
}
like image 89
STW Avatar answered Jan 14 '23 14:01

STW


In ASP MVC 6 you can return an instance of the StatusCodeResult from your controller method:

public IActionResult ConflictAction()
{
    return new StatusCodeResult(StatusCodes.Status409Conflict);
}

Better yet, you could create your own HttpConflictResult class:

public class HttpConflictResult : StatusCodeResult
{
    public HttpConflictResult() : base(StatusCodes.Status409Conflict)
    {
    }
}

public IActionResult ConflictAction()
{
    return new HttpConflictResult();
}

In case you are wondering, those result types are just setting the StatusCode property of the response, so the following would be equivalent to the 2 approaches above based on StatusCodeResult:

public IActionResult ConflictAction()
{
    Response.StatusCode = StatusCodes.Status409Conflict;
    return new EmptyResult();
}
like image 38
Daniel J.G. Avatar answered Jan 14 '23 15:01

Daniel J.G.