Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Authentication ASP核心起始页为登录,但不应为_Authentication_Asp.net Core_Asp.net Mvc Routing_Startup_Website Homepage - Fatal编程技术网

Authentication ASP核心起始页为登录,但不应为

Authentication ASP核心起始页为登录,但不应为,authentication,asp.net-core,asp.net-mvc-routing,startup,website-homepage,Authentication,Asp.net Core,Asp.net Mvc Routing,Startup,Website Homepage,我们的起始页应该是Views/Home/index.cshtml,但由于某些原因,它总是默认为登录页。一切看起来都很正常 我可以导航到https://localhost/Home 没有直接登录,我就无法在直接回家的时候启动它https://localhost Startup.cs: public class Startup { public static IConfiguration Configuration { get; set; } public Startup(IHos

我们的起始页应该是Views/Home/index.cshtml,但由于某些原因,它总是默认为登录页。一切看起来都很正常

我可以导航到https://localhost/Home 没有直接登录,我就无法在直接回家的时候启动它https://localhost

Startup.cs:

public class Startup
{
    public static IConfiguration Configuration { 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)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //Van - 9-29-2019: Cookie policy example: https://quixel.com/cookiepolicy
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
        });

        //services.AddAuthentication(options =>
        //{
        //    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        //    options.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        //    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        //    options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        //    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        //});

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            options.SignIn.RequireConfirmedEmail = false;
            options.Password.RequiredLength = 10;
            options.Password.RequireLowercase = true;
            options.Password.RequireUppercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireDigit = true;
        })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
        services.AddScoped<UserManager<ApplicationUser>>();
        services.AddMemoryCache();
        services.AddDistributedMemoryCache();

        // For session variables, if used. Default IdleTimeout if not accessed = 20 minutes
        services.AddSession(options =>
        {
            options.Cookie.Name = ".H.Session";
            //options.IdleTimeout = TimeSpan.FromMinutes(20);

            //Van - 9-26-2019: Making this essential. The session will hold the evnironment ID if the user has an environment running.
            options.Cookie.IsEssential = true; // GDPR related
        });

        // Microsoft devs discuss expiration settings: https://github.com/aspnet/Identity/issues/1612

        services.Configure<IdentityOptions>(options => 
        {
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(10);
            options.Lockout.MaxFailedAccessAttempts = 3;
            options.Lockout.AllowedForNewUsers = true;
        });

        //Van - 9-26-2019: Added because in asp core 3.0 Synchronous operations are disallowed by default
        //TODO: The line "data = await streamReader.ReadToEndAsync();" in TextPlainInputFormatter.cs is the problem. Should work though, its async. using this temp. workaround
        services.Configure<IISServerOptions>(options =>
        {
            options.AllowSynchronousIO = true;
        });

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;

            //TODO: the timer below works, but does not automatically redirect, it redirects when you navigate to another page. Find a way to refresh on cookie timeout
            //This also only works if pages are being changed. Not useful for range idleness
            //options.ExpireTimeSpan = TimeSpan.FromMinutes(2);
            //options.ExpireTimeSpan = TimeSpan.FromSeconds(5);
            options.SlidingExpiration = true;

            //Van - 9-20-2019: Because RedirectToLogin is being used, is this necessary? Using redirectUri in RedirectToLogin instead.
            //options.LoginPath = "/Identity/Account/Login";
            options.AccessDeniedPath = "/Identity/Account/AccessDenied";

            //Located in CookieEvents.cs
            options.EventsType = typeof(CookieEvents);
            // options.Events.OnRedirectToLogin = delegateclass. to handle whether to stopenvironment and really logout 
            // - what if guac/range activity is ongoing, bad UX to logout and stopenvironment. CookieAuthenticationEvents delegate class
            // - http://codereform.com/blog/post/asp-net-core-2-0-authentication-with-local-logins-responding-to-backend-changes/
        });

        // Looks like this is policy based, not role based
        services.AddMvc(options =>
                {
                    options.InputFormatters.Add(new TextPlainInputFormatter());
                    options.EnableEndpointRouting = false;
                })
                .AddRazorPagesOptions(options =>
                {
                    options.Conventions.AllowAnonymousToPage("/Home/Index");
                    options.Conventions.AddPageRoute("/Identity/Account/Login", "");
                    options.Conventions.AuthorizeAreaPage("Identity", "/Manage/DownloadPersonalData");
                    options.Conventions.AuthorizeAreaPage("Identity", "/Manage/Index");
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                .AddSessionStateTempDataProvider();

        //Van - 9/05/2019 - Exceptions get thrown without this line
        System.Environment.SetEnvironmentVariable("AWS_ENABLE_ENDPOINT_DISCOVERY", "false");
        services.AddDefaultAWSOptions(Configuration.GetAWSOptions());

        services.Configure<ArenaClientOptions>(Configuration.GetSection("ArenaClient"));
        services.Configure<HOptions>(Configuration.GetSection("H"));
        services.Configure<BraintreeOptions>(Configuration.GetSection("Braintree"));

        services.AddScoped<ISubscriptionService, SubscriptionService>();
        services.AddScoped<IDashboardService, DashboardService>();
        services.AddTransient<IArenaClient, ArenaClient>();
        services.AddSingleton<ICacheService, CacheService>();

        services.AddTransient<IEmailSenderService, EmailSenderService>();
        services.Configure<EmailSenderOptions>(Configuration.GetSection("EmailSender"));

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddTransient<CookieEvents>();

        services.AddSingleton<IHubHelperService, HubHelperService>();

        services.AddSignalR();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider provider)
    {
        // TODO: ASP.NET Core diagnostics?

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseExceptionHandler("/Home/Error");
            //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.UseAuthentication();
        //app.UseHttpsRedirection();

        app.UseSession();       
        app.UseStaticFiles();
        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
                Path.Combine(Directory.GetCurrentDirectory(), "Utilities")), RequestPath = "/Utilities"
        });
        //app.UseCookiePolicy();

        app.UseSignalR(routes =>
        {
            routes.MapHub<Hubs.RangeHub>("/range");
        });

        //Van - 9-14-2019 - using MVC with defaults should work just fine sense we are not changing the routes
        //  The home controller is being overridden somewhere else
        app.UseMvcWithDefaultRoute();
        //app.UseMvc(routes =>
        //{
        //    routes.MapRoute(
        //        name: "default",
        //        template: "{controller=Home}/{action=Index}/{id?}");
        //});

        CreateRoles(provider);
    }


    private void CreateRoles(IServiceProvider serviceProvider)
    {
        var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
        var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

        var roleNames = Configuration.GetSection("H:Roles").Get<string[]>();
        var superuserEmail = Configuration.GetSection("H:SuperuserEmail").Get<string>();

        Task<IdentityResult> roleResult;

        foreach (var roleName in roleNames)
        {
            Task<bool> roleExist = RoleManager.RoleExistsAsync(roleName);
            roleExist.Wait();

            if (!roleExist.Result)
            {
                roleResult = RoleManager.CreateAsync(new IdentityRole(roleName));
                roleResult.Wait();
            }
        }

        // Change to appSettings value
        var user = UserManager.FindByEmailAsync(superuserEmail);
        user.Wait();

        if (user?.Result != null)
        {
            var hasRole = UserManager.IsInRoleAsync(user.Result, "Superuser");
            hasRole.Wait();

            if (!hasRole.Result)
            {
                Task<IdentityResult> addToRole = UserManager.AddToRoleAsync(user.Result, "Superuser");
                addToRole.Wait();
            }
        }
    }
}
家庭控制器:

[AllowAnonymous]
public class HomeController : Controller
{

    public HomeController()
    {
    }

    public IActionResult Index()
    {       
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    /// <summary>
    /// This can be access from /Home/ThrowHiddenException.
    /// 
    /// It demonstrates whether exception handling and logging in the H ASP.NET Core 
    /// application is working correctly. A log entry should be made.
    /// 
    /// THEX string is searchable in the logs.
    /// </summary>
    /// <returns></returns>
    public IActionResult ThrowHiddenException()
    {
        throw new Exception("THEX: Test exception handling and logging.");
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
以前有人碰到过这个吗? 据我所知,这可能是因为页面在被访问之前需要进行身份验证,这不是我想要的主页,这是欢迎用户访问站点

更新1:如果我删除Login.cshtml,主页现在可以工作了,但是我当然需要登录页面

更新2:考虑到这可能是一个身份验证问题,我一直在查看我的服务。配置应用程序查看选项和内容。为了以防万一,我把LoginPath注释掉了,但结果是一样的

更新3:sdk安装的屏幕截图:

更新4:重要的是,在日志中我看到:[INF]路由与{page=/Account/Login,area=Identity,action=,controller=}匹配。正在执行页面/帐户/登录

仍然不确定它在代码中发生的位置。太奇怪了。

你的问题是由options.Conventions.AddPageRoute/Identity/Account/Login引起的;这将重定向https://localhost 发送到/Identity/Account/Login


尝试注释掉这一行options.Conventions.AddPageRoute/Identity/Account/Login

我发现了问题。登录razor页面的顶部有@page/,我猜这种路由比启动时可能发生的任何其他路由都要好。删除/修复了该问题。我把我的改为登录


如果其他人有此问题,请查看您的razor页面顶部。

与我们分享您的完整Startup.cs和HomeController。@桃洲我已使用完整HomeController和Startup.cs更新了帖子。结果相同。我仍然可以登录page@Is有没有复制您的问题的演示?目前没有公开演示。我只想创建一个测试Web应用程序,但visual studio抱怨它找不到我的核心sdk。。。再说一遍。@Snipe3000您是如何创建web应用程序的?检查目标框架和当前安装的core sdk。目标框架是core 3.0,其安装和工作正常。一个dotnet-info显示,我上面发布的当前webapp可以很好地使用它。当我尝试创建一个新的核心webapp项目时,它说没有安装sdk,哈哈。