首页 > 解决方案 > 如何在不登录的情况下设置身份?无密码+​​无数据库

问题描述

我想让人们有机会在我的网站上选择用户名。仅针对他们当前的会话,无需登录名、密码和数据库。

我在网上搜索答案,但我找不到真正的答案。也许我只是使用了错误的术语。

知道如何实现吗?

标签: c#asp.net-core-identity

解决方案


要设置当前身份,您可以尝试HttpContext.SignInAsync.

请按照以下步骤操作:

  1. 控制器

    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");
        }
    }
    
  2. 看法

    @{
        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>
    
  3. 配置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?}");
            });
        }
    }
    

推荐阅读