【问题标题】:How do I redirect to a different Razor page without page name string?如何在没有页面名称字符串的情况下重定向到不同的 Razor 页面?
【发布时间】:2020-06-30 10:34:48
【问题描述】:

在我的 ASP.NET Razor Pages 应用程序中,用户通常必须单击一个按钮并被重定向到应用程序的不同(内部)页面。为了保持代码的可维护性,我想避免使用字符串作为页面名称。有没有办法从静态属性或类名中获取页面名称?

public class SomeModel : PageModel
{
    public ActionResult OnPostLogin()
    {
    // Don't want to use string because it's hard to maintain!
    //   return new RedirectResult("AnotherPage");

    // The below is giving a compile error
    // return new RedirectResult(nameof(_Pages_AnotherPage));
    
    // How to get page name directly from class or property?
       return new RedirectResult(AnotherPage....);
    }
}

【问题讨论】:

    标签: asp.net-core razor


    【解决方案1】:

    您可以从 appsettings.json 获取 url。这是一个演示:

    appsettings.json:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "RedirectUrl": "Index"
    }
    

    cshtml.cs:

    public class RedirectPageModel : PageModel
        {
            private readonly IConfiguration _configuration;
            public RedirectPageModel(IConfiguration configuration)
            {
                _configuration = configuration;
            }
            public IActionResult OnGet()
            {
                return Page();
            }
            public IActionResult OnPost()
            {
                var redirectUrl = _configuration["RedirectUrl"];
                return Redirect(redirectUrl);
            }
        }
    

    结果:

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 2017-01-02
      • 2012-04-10
      • 1970-01-01
      • 2019-06-25
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多