Cookie在网络API

时间:2015-08-18 10:15:20

标签: javascript cookies asp.net-web-api

我在web api中使用cookie进行身份验证。在服务器端web api中创建cookie。当我在阅读时,它显示我无效。    另外,我正在使用html ajax发送请求。

用于创建cookie的函数:

public HttpResponseMessage SetCookies()
    {
        var resp = new HttpResponseMessage()`enter code here`;

        HttpClient client = new HttpClient(handler);

        var cookie = new CookieHeaderValue("MyCookie", "12345");
        cookie.Expires = DateTimeOffset.Now.AddDays(1);
        cookie.Domain = Request.RequestUri.Host;
        cookie.Path = "/";

        resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
        return resp;
    } 

创建Cookie后,我尝试使用以下代码读取Cookie:

 CookieHeaderValue cookie = Request.Headers.GetCookies("MyCookie").FirstOrDefault();
            if (cookie != null)
            {
                string sessionId = cookie["MyCookie"].Value;
            }

它总是返回null。

请帮助我如何获取和设置cookie值。

谢谢。

这是java脚本代码:

function setCookie() {
    var cname = " MyCookie";
    var cvalue = "1234fer5678";
    var exdays = 1;
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
function onButtonClick() {
    setCookie();`enter code here`
    $.ajax({
        url: 'http://localhost:49702/v1/user/register',
        type: "GET",
        data: {},
        dataType: 'json',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true
    });      

};

我手动设置了cookie值。我仍然在服务器端api

中获取头请求中的cookie

1 个答案:

答案 0 :(得分:0)

我看过您的javascript代码,在代码crossDomain: true中,我认为您的问题与cross domain有关,您可以试试这个:

$.ajax({
        url: 'http://localhost:49702/v1/user/register',
        type: "GET",
        data: {},
        dataType: 'jsonp', // Notice! jsonp (lowercase)
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true
    });    

更新:查看代码,您可以在设置Cookie时设置domain

var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate 
                  + ";domain=.example.com;path=/";