我想让人们有机会在我的网站上选择用户名。仅用于当前会话,无需登录,密码和数据库。
我正在网上寻找答案,但找不到真正的答案。也许我只是用错了术语。
有什么想法要实现吗?
答案 0 :(得分:2)
要设置当前身份,您可以尝试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?}");
});
}
}