使用ASP.NET Core创建Cookie

20
在ASP.NET MVC 5中,我有以下扩展:
public static ActionResult Alert(this ActionResult result, String text) {
    HttpCookie cookie = new HttpCookie("alert") { Path = "/", Value = text };
    HttpContext.Current.Response.Cookies.Add(cookie);
    return result;
}

基本上我正在添加一个带有文本的cookie。

在ASP.NET Core中,我找不到创建HttpCookie的方法。这不再可能吗?


2
可能是ASP.NET Core rc2中的Cookies的重复问题。 - adem caglin
可能是ASP.NET Core和Cookies的重复问题。 - Michael Freidgeim
如果您需要支持每个Cookie的多个值,可以查看此链接:https://dev59.com/fVcP5IYBdhLWcg3w39s- - Francisco Goldenstein
2个回答

38

你尝试过这样的方法吗:

    public static ActionResult Alert(this ActionResult result, Microsoft.AspNetCore.Http.HttpResponse response, string text)
    {
        response.Cookies.Append(
            "alert",
            text,
            new Microsoft.AspNetCore.Http.CookieOptions()
            {
                Path = "/"
            }
        );

        return result;
    }

您也可能需要在从控制器(或任何调用位置)调用扩展方法时将响应传递给它。例如:

return Ok().Alert(Response, "Hi");

StackOverflow参考


-3

皮卡皮卡

public static ActionResult Alert(this ActionResult result, Microsoft.AspNetCore.Http.HttpResponse response, string text)
    {
        response.Cookies.Append(
            "alert",
            text,
            new Microsoft.AspNetCore.Http.CookieOptions()
            {
                Path = "/"
            }
        );

        return result;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接