简体   繁体   中英

Set Default Redirect For Authorize Tag

Asp.net Core 3+ has some different conventions - bare with me.

I have a controller that I am trying to use Authentication middleware. I used the default 'scaffolding' when creating a new core project in VS2019. Used the MVC project template for asp.net core 3.1.

I have my controller that has the [Authorize] tag.

[Authorize]
public class AgentController : Controller
{
}

In a past life.. I knew where to set the default redirect if Unauthorized.

It is forcing a redirect to /Identity/SignIn -a default set of razor pages that seems to be built in. I need it to redirect to a specific controller/action. Account/SignIn

Here is my startup:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<AgentUser>(options => options.SignIn.RequireConfirmedAccount = false)
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddControllersWithViews();
        //services.AddRazorPages();

    }

    // 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();
            app.UseDatabaseErrorPage();
        }
        else
        {
            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.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
    }

You can configure the specific path in ConfigureServices (in Startup ):

services.ConfigureApplicationCookie(config =>
{
    config.Cookie.Name = "Identity.Cookie";
    config.LoginPath = "/Account/SignIn";
});

When you add services.AddRazorPages() and services.AddControllersWithViews() at the same time, you need to avoid the same routing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM