Redirect Can';t让.net核心MVC将401重定向到/Account/Login

Redirect Can';t让.net核心MVC将401重定向到/Account/Login,redirect,asp.net-identity,asp.net-core-mvc,iis-express,http-status-code-401,Redirect,Asp.net Identity,Asp.net Core Mvc,Iis Express,Http Status Code 401,当我请求的控制器操作是[Authorize]修饰的,而不是重定向到登录页面时,我收到一个401错误 这是一个.net核心mvc应用程序,使用在IIS express上运行的标识模板 当我从program.cs运行应用程序时,重定向到登录的功能正常。 我已经为cookie身份验证添加了明确的指示,以便在配置和服务部分使用/Account/Login重定向,并配置标识以执行此重定向 我不能让它工作。下面是我的StartUp类,我应该更改什么以使其在IIS express中工作 public clas

当我请求的控制器操作是[Authorize]修饰的,而不是重定向到登录页面时,我收到一个401错误

这是一个.net核心mvc应用程序,使用在IIS express上运行的标识模板

当我从program.cs运行应用程序时,重定向到登录的功能正常。 我已经为cookie身份验证添加了明确的指示,以便在配置和服务部分使用/Account/Login重定向,并配置标识以执行此重定向

我不能让它工作。下面是我的StartUp类,我应该更改什么以使其在IIS express中工作

public class Startup
{
    private MapperConfiguration _mapperConfiguration { get; set; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        if (env.IsDevelopment())
        {
            // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
            builder.AddUserSecrets();
        }

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();

        _mapperConfiguration = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new AutoMapperProfileConfiguration());
        });
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


        services.AddIdentity<ApplicationUser, IdentityRole>(
            option => {
                option.Cookies.ApplicationCookie.LoginPath = "/Account/Login";
                option.Cookies.ApplicationCookie.AutomaticChallenge = true;
                option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddDataProtection();

        services.AddMvc();
        services.AddSignalR();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
        services.Configure<AuthMessageSenderOptions>(Configuration);
        services.Configure<IISOptions>(options => options.AutomaticAuthentication = true);
        services.AddSingleton<IMapper>(sp => _mapperConfiguration.CreateMapper());
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, RoleManager<IdentityRole> roleManager)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();



        app.UseStaticFiles();

        app.UseIdentity();

        // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

        //app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "MyCookies",
            SlidingExpiration = true,
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            LoginPath = new PathString("/Account/Login")
        });
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
            routes.MapRoute(
                name: "index",
                template: "{controller=Home}/{id?}",
                defaults: new { action = "Index" });
        });
        app.UseSignalR();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        MyDbInit.Init(context, roleManager);

    }
}
公共类启动
{
私有MapperConfiguration\u MapperConfiguration{get;set;}
公共启动(IHostingEnvironment环境)
{
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,可选:true,重载更改:true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,可选:true);
if(env.IsDevelopment())
{
//有关使用用户机密存储的更多详细信息,请参阅http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration=builder.Build();
_mapperConfiguration=新的mapperConfiguration(cfg=>
{
AddProfile(新的AutoMapperProfileConfiguration());
});
}
公共IConfigurationRoot配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
//添加框架服务。
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
服务附加性(
选项=>{
option.Cookies.applicationcokie.LoginPath=“/Account/Login”;
option.Cookies.applicationcokie.automaticcchallenge=true;
option.Cookies.applicationcokie.AutomaticAuthenticate=true;
})
.AddEntityFrameworkStores();
services.AddDataProtection();
services.AddMvc();
services.AddSignalR();
//添加应用程序服务。
services.AddTransient();
services.AddTransient();
服务。配置(配置);
services.Configure(options=>options.AutomaticAuthentication=true);
services.AddSingleton(sp=>\u mappeConfiguration.CreateMapper());
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void Configure(IApplicationBuilder应用程序、IHostingEnvironment环境、ILoggerFactory loggerFactory、ApplicationDbContext上下文、RoleManager RoleManager)
{
loggerFactory.AddConsole(Configuration.GetSection(“Logging”);
loggerFactory.AddDebug();
app.UseStaticFiles();
app.UseIdentity();
//在下面添加外部身份验证中间件。要配置它们,请参阅http://go.microsoft.com/fwlink/?LinkID=532715
//app.UseStatusCodePagesWithReExecute(“/Home/Error/{0}”);
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationScheme=“mycokies”,
slidengexpiration=true,
自动验证=真,
自动挑战=正确,
LoginPath=新路径字符串(“/Account/Login”)
});
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
routes.MapRoute(
名称:“索引”,
模板:“{controller=Home}/{id?}”,
默认值:new{action=“Index”});
});
app.usesignal();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
Init(上下文,角色管理器);
}
}

身份自动添加cookie身份验证。您将在“配置”中再次添加它


当您添加第二个实例时,您正在设置两个自动属性,因此现在两个中间件正在尝试执行重定向,并且该行为是“未定义的”(其中未定义==“将严重地把事情搞砸”)。

我整晚都遇到同样的问题,无法找到解决方案。直接从Kestrel运行该站点重定向很好,但通过IIS或IIS Express它根本不会重定向-它会转到一个白色页面

在向Identity Git发布相关信息后,我意识到我的模板设置为在框架的1.0.1而不是1.1.0下运行。我将其更新为使用1.1.0,并将所有Nuget软件包更新为1.1.0,现在它在IIS和IIS Express中正确重定向

我不确定软件包是否更新了“修复”了一些不正常的东西,或者这仅仅是1.1.0中修复的1.0.1的问题


这一行在
类中配置
方法,解决me问题:

public class Startup
{
     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
     {
         ...
         app.UseAuthentication(); // <= This line
         app.UseMvc(routes =>
         {
            ...
         });
     }
}
公共类启动
{
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
...
app.UseAuthentication();//
{
...
});
}
}

401
意味着
用户/请求未通过身份验证。
@T–nNguỹn您赢得了所有的互联网。我只是在它失败后才开始排除故障。即使在明确设置重定向之后,它也不是重定向。我在配置中添加的是在401上使用重定向的明确指示。这在独立运行时工作良好。它在IIS中失败。你喜欢夏娃吗