[英]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. 我正在尝试让我的服务发送JSON响应以及状态码,但不确定如何做到这一点。 For example, as a response to the POST request, I'd like to send a 201 Created response.
例如,作为对POST请求的响应,我想发送201 Created响应。 So far what I have is this.
到目前为止,我所拥有的是这个。
EmployeeApiController.cs 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. 现在返回
text/html
而不是JSON。 I tried changing my return type to IHttpActionResult
and then return Json(response)
but that didn't work. 我尝试将返回类型更改为
IHttpActionResult
,然后return Json(response)
但这没有用。 How should that be done? 应该怎么做?
Add [Produces("application/json")]
to your class decoration 将
[Produces("application/json")]
到您的类装饰中
[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 这应该解决问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.