簡體   English   中英

為什么ajax請求會忽略“ Set-Cookie”標頭?

[英]Why is the “Set-Cookie” header ignored with an ajax request?

我一直在胡說八道。 我已經閱讀了多篇文章,並且看到了很多Stackoverflow問題,但是仍然找不到確切的答案。

根據我的閱讀,對ajax請求的響應可以包含“ Set-Cookie”標頭,而該標頭又被瀏覽器接受。 在對相同域的后續請求中,瀏覽器應該將cookie發送回服務器。 (假設它們在同一域中)。

首先,以上是正確的,還是我誤解了一些東西?

其次,假設這是正確的,那么我下面的應用程序中缺少什么? 我在Visual Studio 2015中啟動了一個新的Empty asp.net項目,並為它添加了WEB API組件。 然后,我做了以下控制器:

public class AuthenticationController : ApiController
{
    [Route("api/Authentication/Login/")]
    [HttpPost]
    public HttpResponseMessage Login([FromBody]CredentialContainer credentials)
    {
        var response = new HttpResponseMessage();

        try
        {
            var token = Guid.NewGuid().ToString(); 
            var cookie = new CookieHeaderValue("access_token", token);

            cookie.Expires = DateTimeOffset.Now.AddDays(1);
            cookie.Domain = Request.RequestUri.Host;
            cookie.Path = "/";
            cookie.HttpOnly = true;

            response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
            response.StatusCode = HttpStatusCode.OK;

            return response;
        }
        catch (Exception ex)
        {
            response.StatusCode = HttpStatusCode.InternalServerError;
            return response;
        }
    }

    [Route("api/Authentication/DoSomething")]
    [HttpGet]
    public IHttpActionResult DoSomething()
    {
        var cookie = Request.Headers.GetCookies();
        return Ok();
    }
}

public class CredentialContainer
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

在同一項目中,我添加了一個帶有一些簡單JavaScript的HTML頁面,以調用WEB API。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button onclick="login()">LogIn</button>
<button onclick="doSomething()">DoSomething</button>
<script>
    function login() {
        var xhr = new XMLHttpRequest();
        var data = { UserName: "user", Password: "password" };

        xhr.open("POST", "http://localhost/WebApplication1/api/Authentication/Login/", true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.withCredentials = true; 
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    alert(document.cookie); 
                }
                else {
                    alert("Fail"); 
                }
            }
        }

        xhr.send(JSON.stringify(data));  
    }

    function doSomething() {
        var xhr = new XMLHttpRequest();

        xhr.open("GET", "http://localhost/WebApplication1/api/Authentication/DoSomething/", true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.withCredentials = true;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var response = xhr.response;
            }
        }

        xhr.send();
    }
</script>

此Web應用程序托管在我的本地IIS(非IIS Express)上。 當我單擊登錄按鈕時,響應將返回到客戶端,其中包括“ Set-Cookie”標頭。 我已經用Fiddler驗證過。 但是,瀏覽器會忽略這一點。 每當我通過“ doSomething()”方法發出請求時,cookie都不會發送回去。 我已經在Fiddler和DoSomething()Web API方法中對此進行了驗證。

我知道通過設置HttpOnly = true,JavaScript無法訪問cookie,因此document.cookie將為空白,但是我不明白為什么這樣做會阻止瀏覽器在后續請求中發送它。 我對這東西不知所措。 有人可以闡明問題還是將我指向一個實際工作的.NET示例,該示例實際上根據請求發送cookie?

謝謝

好的,發現問題出在使用本地主機。 Sire為這個問題提供的答案解決了我的問題。

為什么asp.net不在本地主機中創建cookie?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM