【问题标题】:Change Default Page in Web API project .net core 6 MVC在 Web API 项目 .net core 6 MVC 中更改默认页面
【发布时间】:2022-11-14 06:49:25
【问题描述】:

我有 ASP.net 核心 **WebAPI ** 项目,之后我在这个项目中创建了 Scaffolded item witch Identity。如何将默认页面更改为 Identity/page/login.cshtml 而不是 ~/swagger/index.html 谢谢

将默认页面从 ~/swagger/index.html 更改为 Identity/page/login.cshtml 谢谢

我的代码在这里 应用用户.cs

public class AppUser: IdentityUser <int>
    {
        public string FullName { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateModified { get; set; }

    }

程序.cs

builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = $"/Identity/Account/Login";
    options.LogoutPath = $"/Identity/Account/Logout";
    options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});

AppDbContext.cs

public class AppDbContext : IdentityDbContext<AppUser, IdentityRole<int>, int>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) 
         : base(options)
        {
        }
         ...........................................
     }

_LoginPartial.cshtml

@using Claim.Data.Entities
@using Microsoft.AspNetCore.Identity

@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager

当我测试点击登录进入登录页面

错误: InvalidOperationException:尝试激活“XXXXXXX.Areas.Identity.Pages.Account.LoginModel”时,无法解析“Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”类型的服务。

【问题讨论】:

  • 查看 Properties 文件夹中的 LaunchSettings.json 文件和 google"launchUrl": "招摇",
  • 谢谢汤普森,我在 Program.cs builder.Services.AddControllersWithViews().AddRazorPagesOptions(options => { options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", ""); });还修改了 LaunchSettings.Json 在尝试激活“XXXXXXX.Areas.Identity.Pages”时出现此错误 InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'。 Account.LoginModel'。
  • 你能分享你的项目结构吗?屏幕截图或项目层次结构就可以了。
  • 嗨 Md Farid Uddin Kiron 我添加了代码
  • 你能在你的 program.cs 中分享更多关于身份配置的信息吗?

标签: api asp.net-core asp.net-core-mvc


【解决方案1】:

您好已经解决了问题。我必须更改 Login.cshtmal.sc 文件。 但是我遇到了身份验证问题,无法登录

 SignInManager.IsSignedIn(User) <- return claims = 0

_loginPatial.cshtml

    @using Microsoft.AspNetCore.Identity
    
    @inject SignInManager<IdentityUser> SignInManager
    @inject UserManager<IdentityUser> UserManager
    
    <ul class="navbar-nav">
    @if (SignInManager.IsSignedIn(User)) 
    {
        <li class="nav-item">
            <a id="manage" class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
        </li>
        <li class="nav-item">
            <form id="logoutForm" class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
                <button id="logout" type="submit" class="nav-link btn btn-link text-dark">Logout</button>
            </form>
        </li>
    }
    else
    {
        <li class="nav-item">
            <a class="nav-link text-dark" id="register" asp-area="Identity" asp-page="/Account/Register">Register</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" id="login" asp-area="Identity" asp-page="/Account/Login">Login</a>
        </li>
    }
    </ul>

Login.cshtml.cs

if (result.Succeeded) <------ true

    public async Task<IActionResult> OnPostAsync(string? returnUrl = null)
            {
                returnUrl ??= Url.Content("~/");
    
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
    
                if (ModelState.IsValid)
                {
                    // This doesn't count login failures towards account lockout
                    // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                    var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User logged in.");
                        return LocalRedirect(returnUrl);
                    }
    ..............................

program.cs

    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    builder.Services.AddRazorPages();
    builder.Services.AddDbContext<AppDbContext>(opt =>
    {
        opt.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
    });
    
    builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddDefaultTokenProviders()
        .AddEntityFrameworkStores<AppDbContext>();
    
    builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = true,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Constants.SecretKey)),
            ValidateAudience = true,
            ValidIssuer = Constants.Issuer,
            ValidAudience = Constants.Audience,
            RequireExpirationTime = true,
        };
    });
    
    builder.Services.AddScoped<IUserClaimService, UserClaimServices>();
    builder.Services.AddSingleton<IEmailSender, EmailSender>();
    builder.Services.ConfigureApplicationCookie(options =>
    {
        options.LoginPath = $"/Identity/Account/Login";
        options.LogoutPath = $"/Identity/Account/Logout";
        options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
    });
    
    //builder.Services.AddMvc().AddRazorPagesOptions(options =>
    //{
    //    options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", "");
    //}
    //    );
    
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        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.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.MapRazorPages();
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 2021-03-01
    • 1970-01-01
    • 2016-04-25
    • 2023-03-29
    • 2021-12-16
    • 2020-03-23
    • 2014-07-08
    • 1970-01-01
    相关资源
    最近更新 更多