简体   繁体   中英

ASP.NET service send JSON response

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM