我使用ASP.NET核心创建了一个示例web应用程序来测试cookie的存储和检索。不幸的是,我不能存储cookie。
我已经为我的问题阅读了这些问题:
Create cookie with ASP.NET Core
但不幸的是,我没有找到一个好的答案。
我将首先请求一个IndexA操作来存储cookie。代码运行时没有任何错误,但是当我请求IndexB操作时。找不到指定的值
这是IndexA操作:
public IActionResult IndexA()
{
Response.Cookies.Append("mykey", "myvalue",
new CookieOptions()
{
Expires = DateTime.Now.AddMinutes(10)
});
return View();
}
这是IndexB操作:
public IActionResult IndexB()
{
var cookie = Request.Cookies["mykey"];
return View();
}
这是Startup Class:
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?}");
});
}
}
发布于 2019-03-22 22:56:52
我正在使用ASP.NET Core2.2。下面是我的ConfigureServices(IServiceCollection服务)中用来将HttpContextAccessor注入到控制器中的内容。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//... some code
//services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();
}
下面是我的控制器中的内容:
private readonly IHttpContextAccessor _httpContextAccessor;
public MySomethingController(IHttpContextAccessor httpContextAccessor)
{
//... some code
this._httpContextAccessor = httpContextAccessor;
}
下面是Action方法的代码:
[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();
}
然后我有以下方法:
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值,并将其传递给视图。我在家里的控制器里有这个:
...
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();
}
祝好运
发布于 2020-06-30 06:14:12
控制器公开HttpContext.Response.Cookies..。不需要通过ConfigureServices方法使用依赖项注入,也不需要向控制器添加额外的属性。只需调用HttpContext.Response.Cookies.Append(...);
https://stackoverflow.com/questions/51932338
复制相似问题