【问题标题】:Changing Default Page In Asp.Net Core App在 Asp.Net Core 应用程序中更改默认页面
【发布时间】:2023-03-12 09:01:01
【问题描述】:

我正在尝试更改我的 ASP.NET Core MVC C# 应用程序中的起始页。我想先将用户带到一个登录页面,我已将Startup.cs 更改为:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseEndpoints(endpoints =>
    {
       endpoints.MapControllerRoute(
         name: "default",
         pattern: "{controller=Login}/{action=Index}/{id?}");
    }
}

我的控制器看起来像这样

public class LoginController : Controller
{
  public IActionResult Index()
  {
     return View();
  }
}

我有一个名为 Login.cshtml 的页面

我在这里错过了什么?

这是我的startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using eDrummond.Models;

namespace eDrummond
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<eDrummond_MVCContext>();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(opetions =>
                {
                    options.LoginPath = "/Login/Index";
                });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseAuthentication();

            app.UseCors(
                options => options.AllowAnyOrigin()
            );
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Login}/{action=Index}/{id?}");
            });
        }
    }
}

我正在使用 VS2019 并创建了一个 asp.net 核心应用程序,然后选择了 MVC,我所做的只是 Scaffold Tables。所以配置应该是正确的?

【问题讨论】:

  • 您的启动文件中有错字。你的代码真的可以编译吗? ` services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(opetions => { options.LoginPath = "/Login/Index"; });`
  • 查看选项的拼写为opetions

标签: c# asp.net-core-mvc asp.net-core-3.1


【解决方案1】:

您需要考虑身份验证流程。首先你是未经授权的。当您访问任何未经授权的页面时,您希望重定向到您的登录页面,对吗?然后你需要告诉这个程序:

public void ConfigureServices(IServiceCollection services) {
  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    // What kind of authentication you use? Here I just assume cookie authentication.
    .AddCookie(options => 
    {
      options.LoginPath = "/Login/Index";
    });
}

public void Configure(IApplicationBuilder app) {
  // Add it but BEFORE app.UseEndpoints(..);
  app.UseAuthentication();
}

这是一个 stackoverflow 主题,可以解决您的问题:

ASP.NET core, change default redirect for unauthorized

编辑:

事实证明,您可以执行this 之类的操作:

// This method gets called by the runtime. Use this method to add services to the container.

public void ConfigureServices(IServiceCollection services)
{
    // You need to comment this out ..
    // services.AddRazorPages();
    // And need to write this instead:
    services.AddMvc().AddRazorPagesOptions(options =>
    {
        options.Conventions.AddPageRoute("/Login/Index", "");
    });
}

2。编辑:

所以我的第一个答案没有错,但它没有包括对控制器所需的更改。 有两种解决方案:

  1. 您将 [Authorize] 添加到所有控制器,您希望被授权, 例如 IndexModel(位于 /Pages/Index.cshtml.cs)以及何时 输入,程序会看到,用户没有被授权并且会 重定向到 /Login/Index(文件位于 /Pages/Login/Index.cshtml.cs)。那么您就不需要指定 DefaultPolicy 或 FallbackPolicy(FallbackPolicy 参考请参见下面的源代码)
  2. 您可以让程序说,所有控制器都需要 即使未标记 [Authorize] 也已授权。但是你需要 标记您想要未经授权通过的控制器 [允许匿名]。这就是它应该如何实现的:

结构:

/Pages
   Index.cshtml
   Index.cshtml.cs
   /Login
      Index.cshtml
      Index.cshtml.cs
/Startup.cs

文件:

// 文件位于/Startup.cs:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Configuration;

namespace stackoverflow_aspnetcore_59448960
{
    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)
        {
            // Does automatically collect all routes.
            services.AddRazorPages();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    // That will point to /Pages/Login.cshtml
                    options.LoginPath = "/Login/Index";
                }); ;

            services.AddAuthorization(options =>
            {
                // This says, that all pages need AUTHORIZATION. But when a controller, 
                // for example the login controller in Login.cshtml.cs, is tagged with
                // [AllowAnonymous] then it is not in need of AUTHORIZATION. :)
                options.FallbackPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/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.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                // Defines default route behaviour.
                endpoints.MapRazorPages();
            });
        }
    }
}

// 文件位于/Pages/Login/Index.cshtml.cs:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace stackoverflow_aspnetcore_59448960.Pages.Login
{
    // Very important
    [AllowAnonymous]
    // Another fact: The name of this Model, I mean "Index" need to be
    // the same as the filename without extensions: Index[Model] == Index[.cshtml.cs]
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {

        }
    }
}

// 文件位于/Pages/Index.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace stackoverflow_aspnetcore_59448960.Pages
{
    // No [Authorize] needed, because of FallbackPolicy (see Startup.cs)
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {

        }
    }
}

【讨论】:

  • 我根据您的帖子添加了您的代码,但是当我启动我的应用程序时,它仍然会将我带到 index.cshtml 的页面。我正在使用 .NET Core 3.1
  • 您能在此处添加您的 LoginController 的代码吗?
  • 哦,我以为...您没有使用 cshtml 文件?这些文件称为 Razor Pages。
  • 当我从 Visual Studio 2019 启动我的应用程序时,我被带到 localhost:44336 并且它显示 \Views\Home\Index.cshtml - 仍然没有显示我的 \Views\Login\Index.cshtml
  • 哦,我认为 Razor 页面有些不同。我正在使用 .cshtml 页面。我的错。
【解决方案2】:

您应该具有如下所示的文件夹结构。

Views
   Login
      Index.cshtml

默认会带你进入登录页面。

【讨论】:

  • 啊-也许这是我的问题。我的文件夹结构是这样的 \Views\Home\index.cshtml .... \Views\Home\Login.cshtml ..... \Views\Home\Privacy.cshtml
  • 好的 - 所以我镜像了你的目录结构,仍然在 \Views\Home\index.cshtml 处为我提供页面
  • 我创建了一个新项目并尝试使用您的端点配置。它带我直接进入登录页面。我没有看到任何其他原因导致您的问题。看看您是否遗漏了您的问题中未提供给我们的其他内容。
  • 查看我的编辑。我更新了 OP 以包含我的整个 startup.cs 文件。 IDK 为什么事情不工作:(
  • 只是做一个干净,构建然后运行它。我认为您的设置没有任何问题。
猜你喜欢
  • 2021-12-16
  • 2019-10-13
  • 2018-11-14
  • 1970-01-01
  • 2023-03-09
  • 2021-09-25
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多