首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用ASP.NET Core2.0存储和恢复cookies?

如何使用ASP.NET Core2.0存储和恢复cookies?
EN

Stack Overflow用户
提问于 2018-08-20 21:56:42
回答 2查看 13.1K关注 0票数 5

我使用ASP.NET核心创建了一个示例web应用程序来测试cookie的存储和检索。不幸的是,我不能存储cookie。

我已经为我的问题阅读了这些问题:

Cookies in ASP.NET Core rc2

Create cookie with ASP.NET Core

Cookies and ASP.NET Core

但不幸的是,我没有找到一个好的答案。

我将首先请求一个IndexA操作来存储cookie。代码运行时没有任何错误,但是当我请求IndexB操作时。找不到指定的值

这是IndexA操作:

代码语言:javascript
复制
public IActionResult IndexA()
{
   Response.Cookies.Append("mykey", "myvalue",
    new CookieOptions()
    {
        Expires = DateTime.Now.AddMinutes(10)
    });
  return View();
}

这是IndexB操作:

代码语言:javascript
复制
public IActionResult IndexB()
{
   var cookie = Request.Cookies["mykey"];
   return View();
}

这是Startup Class:

代码语言:javascript
复制
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
EN

回答 2

Stack Overflow用户

发布于 2019-03-22 22:56:52

我正在使用ASP.NET Core2.2。下面是我的ConfigureServices(IServiceCollection服务)中用来将HttpContextAccessor注入到控制器中的内容。

代码语言:javascript
复制
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        //... some code
        //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddHttpContextAccessor();
    }

下面是我的控制器中的内容:

代码语言:javascript
复制
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MySomethingController(IHttpContextAccessor httpContextAccessor)
    {
        //... some code
        this._httpContextAccessor = httpContextAccessor;
    }

下面是Action方法的代码:

代码语言:javascript
复制
[HttpGet]
    public IActionResult SomethingToDo()
    {
        //... some code for my controller

        //Section for handling cookies
        //set the key value in Cookie  
        SetCookie("MyOwnKey", "Hello World from cookie", 15.0);

        //read cookie from IHttpContextAccessor 
        string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["MyOwnKey"];
        //or 
        string cookieValueFromRequest = GetCookie("MyOwnKey");

        //Delete the cookie object  
        //RemoveCookie("MyOwnKey");

        ViewData["CookieFromContext"] = cookieValueFromContext;
        ViewData["CookieFromRequest"] = cookieValueFromRequest;

        return View();
    }

然后我有以下方法:

代码语言:javascript
复制
    public string GetCookie(string key)
    {
        return Request.Cookies[key];
    }

    public void SetCookie(string key, string value, double? expireTime)
    {
        CookieOptions option = new CookieOptions();
        if (expireTime.HasValue)
            option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
        else
            option.Expires = DateTime.Now.AddMilliseconds(1);
        Response.Cookies.Append(key, value, option);
    }

    public void RemoveCookie(string key)
    {
        Response.Cookies.Delete(key);
    }

我可以在另一个控制器中看到cookie值,并将其传递给视图。我在家里的控制器里有这个:

代码语言:javascript
复制
...
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly IHostingEnvironment _hostingEnvironment;


    public HomeController(IHostingEnvironment hostingEnvironment, IHttpContextAccessor httpContextAccessor)
    {
        this._hostingEnvironment = hostingEnvironment;
        this._httpContextAccessor = httpContextAccessor;
    }

    public IActionResult Index()
    {
        //read cookie from IHttpContextAccessor 
        string cookieValueFromContext = _httpContextAccessor.HttpContext.Request.Cookies["MyOwnKey"];
        ViewData["CookieFromContext"] = cookieValueFromContext;

        return View();
    }

祝好运

票数 1
EN

Stack Overflow用户

发布于 2020-06-30 06:14:12

控制器公开HttpContext.Response.Cookies..。不需要通过ConfigureServices方法使用依赖项注入,也不需要向控制器添加额外的属性。只需调用HttpContext.Response.Cookies.Append(...);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51932338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档