我怎样才能从Web.Api控制器方法发送的cookie [英] How can I send a cookie from a Web.Api controller method

查看:495
本文介绍了我怎样才能从Web.Api控制器方法发送的cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Web.Api service which has a method that accepts a custom class and returns another custom class:

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

现在我也想送一个cookie回作为HTTP响应的一部分。我该怎么做?

Now I want to also send a cookie back as part of the Http response. How can I do that?

推荐答案

我设法从几个不同的位置信息相结合做到这一点。首先,为了能够轻松地在响应发送的cookie中,Web.Api控制器应返回的实例 System.Net.Http.Htt presponseMessage 类(链接):

I managed to do this by combining information from a few different locations. First, in order to easily be able to send cookies in the response, the Web.Api controller should return an instance of the System.Net.Http.HttpResponseMessage class (link):

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>该请求对象方法。然后,整个交易就变成了:

The trick is in the answer to this question. Use the Request.CreateResponse<T> method on the request object. The whole deal then becomes:

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;
    }
}

这篇关于我怎样才能从Web.Api控制器方法发送的cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆