0

I'm trying to make my service send a JSON response along with a status code, but not really sure how to do that. For example, as a response to the POST request, I'd like to send a 201 Created response. So far what I have is this.

EmployeeApiController.cs

[RoutePrefix("api/employee")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class EmployeeApiController : ApiController
{

    readonly EmployeePersistence persistence;


    public EmployeeApiController()
    {
        persistence = new EmployeePersistence();
    }

    [HttpPost]
    [Route("")]
    public HttpResponseMessage Post([FromBody]EmployeeDto employee)
    {
        long id = persistence.SaveEmployee(employee);

        // create http response
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
        response.Headers.Location = new Uri(Request.RequestUri, String.Format("/api/employee/{0}", id));

        return response;
    }

Now that returns text/html instead of a JSON. I tried changing my return type to IHttpActionResult and then return Json(response) but that didn't work. How should that be done?

wesleyy
  • 2,575
  • 9
  • 34
  • 54

1 Answers1

0

Add [Produces("application/json")] to your class decoration

[Produces("application/json")]
[RoutePrefix("api/employee")]
[EnableCors(origins: "*", headers: "*", methods: "*")]

And change you controller method like this

[HttpPost]
public IActionResult Post([FromBody]EmployeeDto employee)
{
    long id = persistence.SaveEmployee(employee);
    return Created('employee',new {id = id});
}

This should solve the problem

Andre.Santarosa
  • 1,150
  • 1
  • 9
  • 22