【问题标题】:Can't set cookie in ASP.NET 5.0无法在 ASP.NET 5.0 中设置 cookie
【发布时间】:2021-09-12 22:03:24
【问题描述】:

我一直在尝试为用户登录信息设置 cookie,但我不断收到这些错误。

我正在导入所有这些

using System;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

// IDE says these are all unnessary
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;

代码是这样的:

string token = Auth.password(username,password);

HttpCookie cookie = new HttpCookie("token",token);
cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);

这里是错误

C:\xxx\my-server\Pages\Login.cshtml.cs(30,5): error CS0246: The type or namespace name 'HttpCookie' could not be found (are you missing a using directive or an assembly reference?) [C:\xxx\my-server\my-server.csproj]
C:\xxx\my-server\Pages\Login.cshtml.cs(30,29): error CS0246: The type or namespace name 'HttpCookie' could not be found (are you missing a using directive or an assembly reference?) [C:\xxx\my-server\my-server.csproj]
C:\xxx\my-server\Pages\Login.cshtml.cs(32,22): error CS1061: 'IResponseCookies' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'IResponseCookies' could be found (are you missing a using directive or an assembly reference?) [C:\xxx\my-server\my-server.csproj]

我使用命令 dotnet new razor 创建了项目。
我正在使用 vscode。
dotnet 版本为 5.0.301。

【问题讨论】:

  • 根据docs.microsoft.com/en-us/dotnet/api/…IResponseCookiesMicrosoft.AspNetCore.Http命名空间中。
  • @user9938 我已经在使用System.Web,添加Microsoft.AspNetCore.Http 并没有改变任何东西
  • System.Web 不再是 ASP.NET Core 中的东西。 System.Web 是旧的 ASP.NET 框架。
  • @mason 那我该怎么做呢?
  • httpContextAccessor.HttpContext.Response.Cookies.Append("token", token, new CookieOptions { Expires = DateTime.Now.AddDays(30) });这需要注入IHttpContextAccessor httpContextAccessor。

标签: c# asp.net cookies razor


【解决方案1】:

问题已通过将代码更改为:

string token = Auth.password(username,password);

HttpContext.Response.Cookies.Append("token", token, 
    new CookieOptions { Expires = DateTime.Now.AddDays(30) });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-22
    • 2014-05-31
    • 2020-06-29
    • 2011-12-27
    • 2015-05-20
    • 2013-05-02
    • 2013-06-12
    • 1970-01-01
    相关资源
    最近更新 更多