首页 > 解决方案 > 通过作为 SPA 子域的 Asp.net Web Api 设置 cookie

问题描述

我有一个与 Asp.net Web API 通信的单页应用程序(基于 Asp.net MVC)。我想通过 API 设置安全和 HttpOnly cookie 进行身份验证,但所有方法都不起作用,这在我可以找到的互联网上。

网域:www.example.com API:www.api.example.com

我尝试了几种设置cookie的方法;

1)使用属性

public class CookieAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var cookie = new CookieHeaderValue("tokenName", "tokenValue")
        {
            Expires = DateTime.Now.AddDays(30),
            Domain = ".example.com",
            HttpOnly = true,
            Secure = true
        };

        actionExecutedContext.Response.Headers.AddCookies(new[] { cookie });

        base.OnActionExecuted(actionExecutedContext);
    }
}

[Cookie]
[HttpPost]
[Route("cookie")]
public IHttpActionResult SetCookie()
{
    return Ok();
}

2) 通过 HttpContext

[HttpPost]
[Route("cookie")]
public IHttpActionResult SetCookie()
{
   var cookie = new HttpCookie("tokenName")
        {
            Domain = ".example.com",
            Secure = true,
            Expires = DateTime.Now.AddDays(30),
            HttpOnly = true,
            Value = "tokenValue"
        };

        HttpContext.Current.Response.Cookies.Add(cookie);

        return Ok();
}

当我在浏览器上检查 cookie 时,什么也没有。如何从 Web API 设置 cookie?

谢谢。

编辑:(用于解决)

我认为问题与 Asp.net 有关,但事实并非如此。问题是我正在使用 jquery ajax 向 API 创建 cookie 的请求,但缺少“withCredentials”道具,因此我无法设置 cookie。

$.ajax({
            method: "POST",
            url: "/cookie",
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            success: function success(response) {
                // code
            },
            error: function error(response) {
                // code
            }
        });

标签: asp.netajaxasp.net-web-apicookiessetcookie

解决方案


推荐阅读