【问题标题】:Asp.net core 3.1 with Razor Pages redirects to the Index page instead of the intended page带有 Razor 页面的 Asp.net core 3.1 重定向到索引页面而不是预期页面
【发布时间】:2021-08-19 00:39:55
【问题描述】:

我的项目中 Razor 页面的结构如下:

大部分内容都可以在“索引”页面中找到。我正在本地主机上处理我的本地 IIS。当我在浏览器中键入本地主机地址时,索引页面将按预期显示。但是,如果我键入 https://localhost:44352/Logout 以打开 Logout 页面,它会调用 Index 页面的 OnGet 方法并打开该页面,而不是调用 Logout 页面的 OnGet 方法。

这里是Index页面的OnGet方法:

public async Task<IActionResult> OnGetAsync()
    {
        if (HttpContext.Session.GetString("activeModal") != null)
        {
            if (string.IsNullOrEmpty(HttpContext.Session.GetString("showModalOnGet")) == false && HttpContext.Session.GetString("showModalOnGet") == "true")
            {
                HttpContext.Session.SetString("showModalOnGet", "false");
            }
            else
            {
                HttpContext.Session.SetString("activeModal", "");
                HttpContext.Session.SetString("loginStatusColor", "");
                HttpContext.Session.SetString("loginStatusMessage", "");
                HttpContext.Session.SetString("forgottenPassStatusColor", "");
                HttpContext.Session.SetString("forgottenPassStatusMessage", "");
            }
        }
        await ReloadData();
        
        return null;
    }

Logout OnGet 的代码:

public async Task<IActionResult> OnGetAsync()
    {
        await LogOutUser();
        return RedirectToPage("Index");
    }

两个页面都没有在它们的@page 指令之后指定路由。他们的构造函数没有什么特别的。

这是 Startup.cs 类中的代码:

    public void ConfigureServices(IServiceCollection aServices)
    {
        Log.Information("Configuring Services");

        /// Add caching of the static files
        aServices.AddResponseCaching();

        /// Add support for Razor
        aServices.AddRazorPages();

        aServices.Configure<CookiePolicyOptions>(options =>
        {
            /// This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
            options.Secure = CookieSecurePolicy.Always;
        });

        /// Add the database connection
        string lConnectionString = mEnvironment.IsDevelopment() ? "LocalDB" : "ServerDB";
        aServices.AddDbContext<DB_Spa_WellnessContext>(options =>
        {
            options.UseSqlServer(mConfiguration.GetConnectionString(lConnectionString));
        });

        /// Add session to store data
        /// Use memory cache for the session
        aServices.AddDistributedMemoryCache();
        aServices.AddSession(options =>
        {
            options.Cookie.Name = ".Spa_Wellness.Session";
            options.IdleTimeout = TimeSpan.FromMinutes(2.0);
        });

        /// Add the configuration of the email client
        aServices.AddSingleton<IEmailConfiguration>(mConfiguration.GetSection("EmailConfiguration").Get<XEmailConfiguration>());

        /// Add the Email Service
        aServices.AddTransient<IEmailService, XEmailService>();

        // Add the configuration of the security service
        aServices.AddSingleton<ISecurityConfiguration>(mConfiguration.GetSection("SecurityConfiguration").Get<XSecurityConfiguration>());

        // Add the Security Service
        aServices.AddTransient<ISecurityService, XSecurityService>();

        /// Add the configuration of the Google Invisible Captcha
        string lCaptchaSection = mEnvironment.IsDevelopment() ? "GoogleInvisibleCaptchaDev" : "GoogleInvisibleCaptcha";
        aServices.AddSingleton<ICaptchaKeys>(mConfiguration.GetSection(lCaptchaSection).Get<XGoogleInvisibleCaptchaKeys>());

        /// Add the service for obtaining user IP and cookies
        aServices.AddHttpContextAccessor();
        aServices.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

        /// HTML minification (https://github.com/Taritsyn/WebMarkupMin)
        aServices
            .AddWebMarkupMin(options =>
            {
                options.AllowMinificationInDevelopmentEnvironment = true;
                options.DisablePoweredByHttpHeaders = true;
            })
            .AddHtmlMinification(options =>
            {
                options.MinificationSettings.RemoveOptionalEndTags = false;
                options.MinificationSettings.WhitespaceMinificationMode = WhitespaceMinificationMode.Safe;
            });
        aServices.AddSingleton<IWmmLogger, WmmNullLogger>(); // Used by HTML minifier

        /// Minification with WebOptimizer (https://github.com/ligershark/WebOptimizer)
        aServices.AddWebOptimizer(pipeline =>
        {
            pipeline.MinifyJsFiles();
            pipeline.MinifyCssFiles();
        });
    }

    
    public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        /// Taken from MiniBlog to disable sniffing
        app.Use((context, next) =>
        {
            context.Response.Headers.Add("X-Xss-Protection", "1");
            context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
            context.Response.Headers.Add("X-Frame-Options", "DENY");
            context.Response.Headers.Add(
                    "Content-Security-Policy",
                    "form-action 'self'; ");
            /// Cache control
            context.Response.GetTypedHeaders().CacheControl =
                new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                {
                    Public = true,
                    MaxAge = TimeSpan.FromDays(365)
                };
            context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
                new string[] { "Accept-Encoding" };

            return next();
        });

        /// Minification with WebOptimizer (https://github.com/ligershark/WebOptimizer)
        app.UseWebOptimizer();

        /// Always redirect to HTTPS
        app.UseHttpsRedirection();

        /// Use static files and caching
        app.UseStaticFiles();
        app.UseRouting();
       // app.UseResponseCaching();

        app.UseCookiePolicy();

        app.UseSession();

        /// HTML minification (https://github.com/Taritsyn/WebMarkupMin)
        /// TODO: Send web page to the developer
        app.UseWebMarkupMin();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapRazorPages();
        });
    }

我不知道您是否有任何其他代码片段可能感兴趣。

另一个有趣的部分是 ControlPanel 文件夹中的页面显示没有任何问题。错误和隐私页面也可以正常工作。问题似乎出在新添加的页面上。

我注意到的另一件事。如果我在索引页面上使用查询字符串,则查询字符串的结果为空,而不是获取在浏览器中键入的内容。

忘了说有时会打开 Logout 页面并调用其 OnGet 方法,但大多数时候会打开 Index 页面。

我感觉我的启动配置有问题,但是是什么。

【问题讨论】:

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


    【解决方案1】:

    首先,确保索引页面与 OnGetAsync 方法位于同一控制器中。 如果没有,我建议使用RedirectToAction("Action", "Controller");

    我希望我能有所帮助。

    【讨论】:

    • 感谢您的建议。但是,问题仍然存在。我尝试了 RedirectToRoute() 和 Response.Redirect() 但问题仍然存在。似乎正在发生一些缓存。
    【解决方案2】:

    花了更多时间调试后,我发现了导致问题的原因。 Startup.cs 中的以下代码似乎是问题所在:

    app.Use((context, next) =>
            {
                context.Response.Headers.Add("X-Xss-Protection", "1");
                context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
                context.Response.Headers.Add("X-Frame-Options", "DENY");
                context.Response.Headers.Add(
                        "Content-Security-Policy",
                        "form-action 'self'; ");
                /// Cache control
                /*context.Response.GetTypedHeaders().CacheControl =
                    new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromDays(365)
                    };
                context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] =
                    new string[] { "Accept-Encoding" };*/
    
                return next();
            });
    

    我评论的最后几行似乎是导致问题的原因。在我将它们注释掉之后,一切正常(现在)。我假设这里的一些缓存导致服务器返回索引页面而不是注销页面。

    无论如何,现在一切正常。

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 2020-05-06
      • 2019-06-25
      • 2020-05-25
      • 1970-01-01
      • 2020-07-09
      • 2021-02-21
      • 2021-08-17
      • 2019-03-12
      相关资源
      最近更新 更多