web-dev-qa-db-ja.com

Asp.Net Coreアプリのデフォルトページの変更

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テーブルだけです。 SO設定は正しいはずですか?

1
HotTomales

認証フローを考慮する必要があります。まず、あなたは無許可です。許可されていないページにアクセスした場合、ログインページにリダイレクトしますか?次に、これをプログラムに伝える必要があります。

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コア、無許可のデフォルトリダイレクトを変更

編集:

あなたは 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。編集:

だから私の最初の答えは間違っていなかったが、それはそれが必要とするであろうコントローラへの変更を含んでいなかった。 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()
        {

        }
    }
}
4
Teroneko

以下に示すようなフォルダ構造が必要です。

Views
   Login
      Index.cshtml

デフォルトではログインページが表示されます。

1
Venky