Christopher Pisz
Christopher Pisz

Reputation: 4010

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?

Upvotes: 4

Views: 3886

Answers (4)

Kaptein Babbalas
Kaptein Babbalas

Reputation: 1108

 public async Task<IActionResult> Foo(string sequenceId)
    {                     
            var response = new ContentResult()
            {
                StatusCode = StatusCodes.Status409Conflict,
                Content = "Order duplicate"
            };
            return response;           
    }

I think this is a cleaner way

Upvotes: 0

Daniel J.G.
Daniel J.G.

Reputation: 35022

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();
}

Upvotes: 5

STW
STW

Reputation: 46394

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); 
}

Upvotes: 6

BrunoMartinsPro
BrunoMartinsPro

Reputation: 1856

You are looking for HttpStatusCode

Namespaces

using System.Net.Http;
using System.Web.Http;

You use it like

public HttpResponseMessage ConflictSample()
{
   return Request.CreateResponse(HttpStatusCode.Conflict, "Conflict");
}

Upvotes: 1

Related Questions