c# - 如何在不登录的情况下设置身份?无密码+无数据库
问题描述
我想让人们有机会在我的网站上选择用户名。仅针对他们当前的会话,无需登录名、密码和数据库。
我在网上搜索答案,但我找不到真正的答案。也许我只是使用了错误的术语。
知道如何实现吗?
解决方案
要设置当前身份,您可以尝试HttpContext.SignInAsync
.
请按照以下步骤操作:
控制器
public class HomeController : Controller { public IActionResult Index() { List<SelectListItem> select = new List<SelectListItem> { new SelectListItem("Tom","Tom"), new SelectListItem("Jack","Jack"), new SelectListItem("Vicky","Vicky") }; ViewBag.Select = select; return View(); } [HttpPost] public async Task<IActionResult> Login(string userName) { await HttpContext.SignOutAsync(); var identity = new ClaimsIdentity(); identity.AddClaim(new Claim(ClaimTypes.Name, userName)); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(principal); return RedirectToAction("Index"); } }
看法
@{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div> <div> Hi @User?.Identity?.Name; </div> <form asp-action="Login" method="post"> <select name="userName" class="form-control" asp-items="@ViewBag.Select"></select> <input type="submit" value="Login" /> </form>
配置
Startup.cs
为启用身份验证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.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // 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"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }
推荐阅读
- python - 在openpyxl中更改图表的轴格式?
- swift - 如何在 OSX 上的 Swift 中检测网络接口的 IP 地址变化
- linux - 如何在运行时加载 strongswan 插件
- jquery - 删除已从另一个下拉菜单中选择但未使用 value 属性的下拉值
- python - 找出一个元组是否包含在另一个在 Python 中重复的元组中
- assembly - x86 处理器中的同胞字节是如何形成的?
- javascript - POST 响应后页面内容未更新
- flutter - 循环使用 Flutter 生成 2 列的列表
- python - 如何禁用柱状列中的文本换行?
- cordova - ionic - 为 web 构建,index.html 寻找不存在的文件