从客户端向网络发送 cookie api

Sending cookie from client to web api

在我的客户端(MVC 应用程序的控制器)我使用下面的代码设置 cookie 值:

HttpCookie cookie = new HttpCookie("TestCookie");
cookie.value = 'Test';
HttpContext.Request.Cookies.Add(cookie);

我也在请求中设置 cookie 值 header。这是在我配置 breeze entitymanager 时完成的。我使用 breeze 查询从网络 api.

获取数据
'Cookie': UserProfileID = config.getCookies('UserProfileID')

但是在 Web API 中,我总是发现请求中没有 cookie header。

request.Headers.GetCookies("UserProfileID").FirstOrDefault()

要设置 cookie,您需要将其添加到 Response object,而不是 Request

var cookie = new HttpCookie("TestCookie");
cookie.Value = "Test";
HttpContext.Response.Cookies.Add(cookie);

经过更多研究,我发现 this question。答案提供了一些关于 Web 本质的见解 API:

There's not a whole lot to work with here, but generally speaking, Web API diverges from MVC mostly in that it's fully REST-compliant, whereas MVC is not. REST-compliant applications are stateless (in other words: no session, no cookies, etc.). Everything the API endpoint needs must be sent along with the request either in the URL, the request headers or the request body. That means you could send the value of the cookie (not the cookie, itself) in the query string of a GET request or the body of a POST, or as is typical with REST API auth, as an Authorization HTTP header.

因此,要获得所需的结果,您需要在 MVC 应用程序中提取客户端上的 cookie 值,然后将其作为 API 请求数据的一部分发送,或者使用建议的授权 HTTP header。