简体   繁体   English

如何在 C# 代码中创建 Razor Page Urls?

[英]How does one create Razor Page Urls in C# code?

Microsoft introduced Razor Pages in ASP.NET Core 2.0 as an alternative to MVC. Microsoft 在 ASP.NET Core 2.0 中引入了Razor Pages作为 MVC 的替代方案。 We are looking to migrate our legacy ASP.NET MVC 5 app to NET Core and Microsoft recommends using Razor Pages instead of MVC moving forward.我们希望将我们的旧 ASP.NET MVC 5 应用程序迁移到 NET Core,Microsoft 建议使用 Razor Pages 而不是 MVC 向前推进。

We are currently using T4MVC framework to help generate strongly-typed ActionResult objects to construct complex navigation menus.我们目前正在使用T4MVC框架来帮助生成强类型的 ActionResult 对象来构建复杂的导航菜单。 The nav menu is created using a viewmodel which is a linked list of ActionResult routes where each route can be something quite complex such as:导航菜单是使用视图模型创建的,该视图模型是 ActionResult 路由的链接列表,其中每个路由都可能非常复杂,例如:

https://example.com/Client/1/Documents/2/Edit?p1=123&p2=ABC&h2=456 https://example.com/Client/1/Documents/2/Edit?p1=123&p2=ABC&h2=456

In T4MVC I can add this controller action to my viewmodel with:在 T4MVC 中,我可以使用以下命令将此控制器操作添加到我的视图模型中:

menu.Add(MVC.Client.Documents.Edit(cliendId, documentId, requestParameters));

The ASP documentation doesn't go into detail on how to create routes in code, other than a simple: RedirectToPageResult("./Index") so how does one build more complex page routes without the benefit of T4MVC or resorting to magic strings? ASP 文档没有详细介绍如何在代码中创建路由,除了一个简单的: RedirectToPageResult("./Index") 那么如何在没有 T4MVC 的好处或诉诸魔法字符串的情况下构建更复杂的页面路由?

You can easily hard code the URL if you know the name of the path of the razor page relative to the Pages folder(this is by default).For example:如果您知道 razor 页面相对于 Pages 文件夹的路径名称(这是默认设置),则可以轻松地对 URL 进行硬编码。例如:

 public IActionResult OnPostGoogle(string provider)
        {

            var redirectUrl = "https://localhost:5001/UserPages/ExternalLoginCallback";
            var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
            return new ChallengeResult(provider, properties);
        }

This is a method that configure Google login and redirects user to ExternalLoginCallback page.这是一种配置 Google 登录并将用户重定向到 ExternalLoginCallback 页面的方法。 Here I have ExternalLoginCallback.cshtml.cs that is in Pages/UserPages.这里我有一个位于 Pages/UserPages 中的 ExternalLoginCallback.cshtml.cs。 So you can append a relative path to your page from PagesFolder to your website address or in my case localhost and you will get full url to your page.That is why they used in example RedirectToPageResult("./Index") because Index.cshtml.cs is directly in Pages folder.因此,您可以将 PagesFolder 中页面的相对路径附加到您的网站地址或在我的情况下为 localhost,您将获得页面的完整 url。这就是他们在示例 RedirectToPageResult("./Index") 中使用的原因,因为 Index.cshtml .cs 直接在 Pages 文件夹中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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