我设法通过结合来自几个不同位置的信息来做到这一点。首先,为了能够轻松地在响应中发送 cookie,Web.Api 控制器应该返回一个System.Net.Http.HttpResponseMessage
类的实例(链接):
public class TestController : ApiController
{
public HttpResponseMessage Post([FromBody]CustomRequest request)
{
var resp = new HttpResponseMessage();
...
//create and set cookie in response
var cookie = new CookieHeaderValue("customCookie", "cookieVal");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;
}
}
但是,我如何确保我也可以轻松地寄回CustomResponse
?
诀窍在于这个问题的答案。使用请求对象上的方法。然后整个交易变成:Request.CreateResponse<T>
public class TestController : ApiController
{
public HttpResponseMessage Post([FromBody]CustomRequest request)
{
// process request
...
var resp = Request.CreateResponse<CustomResponse>(
HttpStatusCode.OK,
new CustomResponse() { ... }
);
//create and set cookie in response
var cookie = new CookieHeaderValue("customCookie", "cookieVal");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;
}
}