我正在尝试让我的服务发送JSON响应以及状态代码,但不确定如何做到这一点。例如,作为对POST请求的响应,我想发送201 Created响应。到目前为止我所拥有的就是这个。
EmployeeApiController.cs
const createMarkUp = (id) => {
const markUp = `<div class="tile tile--game" data-name="${id}">
<div class="tile__side tile__side--front">
</div>
<div class="tile__side tile__side--back">
<img src="img/${id}.svg" alt="${id}" class="tile__img">
</div>
</div>`;
return markUp;
};
//...
const compare = (e) => {
guesses.add(e.currentTarget);
if (guesses.size !== 2) return;
if (new Set(Array.from(guesses, guess => guess.dataset.name)).size == 1) {
console.log("win");
guesses = new Set;
return;
}
setTimeout(() => {
for (let guess of guesses) {
guess.classList.remove("tile--active");
}
guesses = new Set;
}, 500);
}
现在返回[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;
}
而不是JSON。我尝试将我的返回类型更改为text/html
然后IHttpActionResult
,但这不起作用。应该怎么做?
答案 0 :(得分:0)
将[Produces("application/json")]
添加到您的班级装饰
[Produces("application/json")]
[RoutePrefix("api/employee")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
并改变你这样的控制器方法
[HttpPost]
public IActionResult Post([FromBody]EmployeeDto employee)
{
long id = persistence.SaveEmployee(employee);
return Created('employee',new {id = id});
}
这应解决问题