在Asp.Net Core App中更改默认页面

时间:2019-12-23 00:00:19

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

我正在尝试在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。所以配置应该正确吗?

2 个答案:

答案 0 :(得分:4)

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

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]标记也被授权。但是那你需要 标记您要未经授权通过的控制器 [AllowAnonymous]。然后应按照以下方式实施:

结构:

/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()
        {

        }
    }
}

答案 1 :(得分:1)

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

Views
   Login
      Index.cshtml

默认情况下,应该带您登录页面。