ASP.NET Core Razor 页面登陆索引页面而不是登录页面

问题描述 投票:0回答:1

我使用 ASP.NET Core 创建了 Razor Pages 应用程序。我的起始页面应该是我使用 ASP.NET Core 身份验证创建的登录页面。当我在计算机上构建和测试应用程序时,一切都按预期运行。但是,在我发布应用程序后,应用程序在索引页面而不是登录页面启动。

这是我的program.cs文件:

using InvoicesApplication.Data;
using InvoicesApplication.Data.Repositories;
using InvoicesApplication.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging.AzureAppServices;
using OfficeOpenXml;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

var builder = WebApplication.CreateBuilder(args);

ExcelPackage.LicenseContext = LicenseContext.NonCommercial; // Set the EPPlus license context

// Add services to the container.
// Dependency Injections

builder.Services.AddRazorPages();

builder.Services.AddDbContext<InvoicesAppContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("InvoicesApplication"))); // Set up DI for database connection

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<InvoicesAppContext>(); // add identity 

// Add authentication and authorization
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Identity/Account/Login";
        options.AccessDeniedPath = "/Identity/Account/Login";
    });

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

// Add the hosted service to DI
builder.Services.AddHostedService<EmailReminderTaskHostedService>();

builder.Services.AddScoped<ICustomerRepository, CustomerRepository>(); // Set up DI for the data (customer repository data)
builder.Services.AddScoped<IItemRepository, ItemRepository>(); // Set up DI for the data (item repository)
builder.Services.AddTransient<IEmailSender, EmailSender>(); // transient means that every time we want to send an email a new instance of the email sender service is created. 

builder.Services.AddTransient<IEmailReminderTask, EmailReminderTask>();

var app = builder.Build();

// Seed the database and apply migrations
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var context = services.GetRequiredService<InvoicesAppContext>();
        context.Database.Migrate(); // Apply any pending migrations

        var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
        SeedData.SeedUsersAsync(userManager).Wait(); // Seed users
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred while migrating the database.");
    }
}

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}
else
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication(); // Ensure the authentication middleware is added
app.UseAuthorization(); // Ensure the authorization middleware is added

app.MapRazorPages();

app.Run();

public static class SeedData
{
    public static async Task SeedUsersAsync(UserManager<IdentityUser> userManager)
    {
        // Define the users to be added
        var users = new List<(string Email, string Password)>
        {
           //removed sensitive information
        };

        foreach (var user in users)
        {
            if (await userManager.FindByEmailAsync(user.Email) == null)
            {
                var identityUser = new IdentityUser
                {
                    UserName = user.Email,
                    Email = user.Email,
                    EmailConfirmed = true
                };

                var result = await userManager.CreateAsync(identityUser, user.Password);
                if (!result.Succeeded)
                {
                    throw new Exception($"Failed to create user {user.Email}: {string.Join(", ", result.Errors.Select(e => e.Description))}");
                }
            }
        }
    }
}

这是我的索引页面的顶部:

@page
@using InvoicesApplication.Data.Models;
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

以及相关的页面模型:

namespace InvoicesApplication.Pages
{
    [Authorize]
    public class IndexModel : PageModel
    {
        private ICustomerRepository _customerRepo;
        private IItemRepository _itemRepo;
        private IEmailSender _emailSender;
        private IEmailReminderTask _emailReminderTask;
        private ILogger<IndexModel> _logger; // register logger service

这些分别是我的登录页面和页面模型的顶部:

@page
@model LoginModel

@{
    ViewData["Title"] = "Log in";
}

<div>

    <div class="container-md align-content-center">

namespace InvoicesApplication.Areas.Identity.Pages.Account
{
    public class LoginModel : PageModel
    {
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly ILogger<LoginModel> _logger;

这是我迄今为止尝试过的:

  • 我在 Program.cs 中将属性 [Authorize] 应用于所有页面和全局。
  • 我使用正确的身份验证和授权设置配置了 Program.cs。
  • 我添加了 JS 控制台日志以查看是否先加载登录页面,然后加载索引页面(登录页面从不加载)。
  • 我添加了用户及其密码,以便在数据库中拥有某些内容(我只是在尝试)。
  • 我尝试过 Mike Brind 的 解决方案,它要求将登录页面设为主页。我收到模糊匹配错误(索引页面和登录页面)。
  • 我尝试在模板中指定路由,即@page“/Index”和@page“/Identity/Account/Login”,但又什么也没有。

如果有人可以提供有关如何解决此问题的任何见解,我将不胜感激。

提前谢谢您。

asp.net-core deployment razor-pages asp.net-authorization
1个回答
0
投票

问题是program.cs中的这段代码:

// Add authentication and authorization
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Identity/Pages/Account/Login";
        options.AccessDeniedPath = "/Identity/Pages/Account/AccessDenied";
    });

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

当我删除它时,一切都按预期进行。我不确定,因为我是 ast.net core 的新手,但既然它可以工作,那么我就很好了。如果有人可以阐明它,那就太好了。

© www.soinside.com 2019 - 2024. All rights reserved.