使用ASP.NET Core创建cookie [英] Create cookie with ASP.NET Core

查看:535
本文介绍了使用ASP.NET Core创建cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET MVC 5中,我具有以下扩展名:

In ASP.NET MVC 5 I had the following extension:

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.

Basically I am adding a cookie with a text.

在ASP.NET Core中,我找不到创建HttpCookie的方法.

In ASP.NET Core I can't find a way to create the HttpCookie.

这不可能吗?

推荐答案

您是否尝试过以下方法:

Have you tried something like:

    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;
    }

您可能还必须在调用中将响应从控制器(或从何处调用)传递给扩展方法.例如:

You may also have to pass the Response in your call to the extension method from the controller (or wherever you call it from). For example:

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

StackOverflow参考

这篇关于使用ASP.NET Core创建cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆