【发布时间】: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/…,
IResponseCookies在Microsoft.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。