23

我有一个 Web.Api 服务,它有一个接受自定义类并返回另一个自定义类的方法:

public class TestController : ApiController
{
    public CustomResponse Post([FromBody]CustomRequest request)
    {
        // process request
        ...
        // create response
        CustomResponse resp = new CustomResponse() { ... };
        return resp;
    }
}

现在我还想将 cookie 作为 Http 响应的一部分发回。我怎样才能做到这一点?

4

2 回答 2

36

我设法通过结合来自几个不同位置的信息来做到这一点。首先,为了能够轻松地在响应中发送 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;
    }
}
于 2013-05-31T09:43:10.167 回答
3

使用最新版本的 Web API、asyncIHttpActionResult,我们现在可以简单地执行此操作:

public async Task<IHttpActionResult> MyMethod(... myParameters ...)
{
    ...
    var cookie = new CookieHeaderValue("myCookie", "myValue");
    ...

    var resp = new HttpResponseMessage();
    resp.StatusCode = HttpStatusCode.OK;
    resp.Headers.AddCookies(new[] { cookie });
    return ResponseMessage(resp);
}
于 2018-08-09T13:41:05.747 回答