Net Core MVC更改URL路由参数为#片段

问题描述

我希望我的最终route参数在页面加载后变成URL片段。

所以,如果我提交如下网址:

https://mysite/controller/param1/param2

它通过我设置的路线命中了我的控制器方法

public ActionResult Index(string param1,string param2) 

如何以某种方式重新路由此路由,以使生成的加载页面显示

https://mysite/controller/param1#param2

解决方法

您可以使用RedirectToAction()重载之一,该重载采用片段参数来生成带有片段的URL:

公共虚拟RedirectToActionResult RedirectToAction(字符串actionName,字符串controllerName,字符串片段);

但是首先,您需要设置一条路由,以将诸如https://mysite/controller/param1/param2之类的请求映射到可以从URL中删除那些参数并调用RedirectToAction()重载的东西。我创建了一个名为FragmentController的单独控制器,并在其中声明了一个名为Process()的方法:

// Startup.cs
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
    ...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "fragment",pattern: "fragment/{controllerName}/{actionName}/{fragmentName}",defaults: new { controller = "fragment",action = "process" });

        endpoints.MapControllerRoute(...);
    });
}

看到新的路由映射正在寻找以/fragment开头,后跟3个参数的任何请求,并且这些参数将正确映射到Process()中的FragmentController操作:

// FragmentController.cs
public class FragmentController : Controller
{
    public IActionResult Process(string controllerName,string actionName,string fragmentName)
    {
        // You can do anything you want with those parameters,i.e.,validations
        return RedirectToAction(actionName,controllerName,fragmentName);
    }
}

就是这样。因此,如果收到https://localhost:44370/fragment/home/privacy/heading1之类的请求

enter image description here


它将正确映射到片段控制器的流程操作:

enter image description here


调用RedirectToAction()重载后,它将正确地重定向到控制器和所需的操作,并带有片段:

enter image description here