我有两个项目,一个是客户端,另一个是API提供者。当我向api提供商发送请求时,请求.Headers.GetCookies()'在客户端部分有值,但在
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var test1 = context.Request.Headers.ToList().FirstOrDefault(h => h.Key == "Cookie");
test1为空并且在
中public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var test2 = actionContext.Request.Headers.GetCookies();
test2为null,这是我发送请求的方式:
[HttpPost]
public ActionResult PostToApiProvider(RequestViewModel requestModel)
{
var request = new HttpResponseMessage();
// Here I add cookie header in request for authentification
if (HttpContext.Request.Cookies.Count != 0)
{
var cookieList = new List<string>();
for (var i = 0; i < Request.Cookies.Count; i++)
{
cookieList.Add(Request.Cookies[i].Value);
}
request.Headers.Add("Cookie", cookieList);
}
var response = client.SendAsync(request).Result;
var testRequestCookies = request.Headers.GetCookies();
return View("SomeView", model)
request和testRequestCookies(调用api提供程序之前和之后)将有cookie值,请参阅屏幕截图:
如果我可以提供更多代码,请询问。谢谢:))
答案 0 :(得分:0)
这是获取Cookie值的方法
private async Task<string> GetCookieValue(string url, string cookieName)
{
var cookieContainer = new CookieContainer();
var uri = new Uri(url);
using (var httpClientHandler = new HttpClientHandler
{
CookieContainer = cookieContainer
})
{
using (var httpClient = new HttpClient(httpClientHandler))
{
await httpClient.GetAsync(uri);
var cookie = cookieContainer.GetCookies(uri).Cast<Cookie>().FirstOrDefault(x => x.Name == cookieName);
return cookie?.Value;
}
}
}