本文介绍了ASP.NET Core 3.1 Cookie未附加Razor页面C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
没有使用以下代码将Cookie添加到页面,我曾尝试向选项中添加必要的内容,但不起作用。使用ASP.NET Core 3.1 Razor页面。以下是我的大部分启动代码和附加的Cookie代码。Startup.cs
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.AddRazorPages();
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
services.AddHttpContextAccessor();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSignalR();
services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddNewtonsoftJson();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseRequestLocalization();
app.UseStaticFiles();
app.UseCookiePolicy();
app.useAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
添加Cookie
string key = "Cookie";
var cookieValue = Request.Cookies[key];
if(cookieValue == null)
{
string value = "true";
var cookieOptions = new CookieOptions()
{
Path = "/",
HttpOnly = false,
IsEssential = true,
Expires = DateTime.Now.AddDays(1),
};
HttpContext.Response.Cookies.Append(key, value, cookieOptions);
}
建议添加is Essential以覆盖CookiePolicy,但这并没有解决任何问题。 DevTools应用程序仅显示.AspNetCore.Identity.Application和.AspNetCore.Antigery Cookie。
编辑: 通过更改解决
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.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
推荐答案
我认为您的创业计划中漏掉了一行
app.UseAuthentication();
它将身份验证中间件添加到您的应用程序中。
您必须在app.UseAuthorization();
如图所示:
app.UseRequestLocalization();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
如果您按照https://docs.microsoft.com/es-es/aspnet/core/security/authentication/identity?view=aspnetcore-3.1&tabs=visual-studio中的说明操作,它应该可以正常工作。
这篇关于ASP.NET Core 3.1 Cookie未附加Razor页面C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!