简体   繁体   English

我如何在 Asp.net 核心中使用 Map 动态网址

[英]How can I Map Dynamic Urls in Asp.net core

So my plan is所以我的计划是

/somewhere/{Dir}/{SubDIr}/{File}

somewhere is a route to handle this part of directories and Sub Directories, my problem is that I couldn't find a way to route that, I tried rewriting a Url, but that's not what i need. somewhere是处理这部分目录和子目录的路由,我的问题是我找不到路由的方法,我尝试重写 Url,但这不是我需要的。 Also I don't know how many subdirs I will have, which makes the process even more difficult.另外我不知道我会有多少子目录,这使得这个过程更加困难。

On the other hand a great example of what I have been looking to achieve is GitHub.另一方面,我一直在寻求实现的一个很好的例子是 GitHub。 you see, the first part of their url is static, which is https://github.com/{User}/{Repo}你看,他们的url的第一部分是static,也就是https://github.com/{User}/{Repo}

and then the dynamic part comes:然后是动态部分:

  • https://github.com/{User}/{Repo}/tree/{branch} to see the base of repo. https://github.com/{User}/{Repo}/tree/{branch}查看 repo 的基础。
  • https://github.com/{User}/{Repo}/blob/{branch}/{dirs}/{file} to see specific files. https://github.com/{User}/{Repo}/blob/{branch}/{dirs}/{file}查看具体文件。

I am looking to do exactly that我正在寻找这样做

Solution:解决方案:

So, After Searching a lot, I found what they call a Match-all parameter, which can be used like:所以,在搜索了很多之后,我找到了他们所谓的 Match-all 参数,它可以像这样使用:

Program.cs .,Needs to be in all Applications running in .net core 3.1 or lower, i test without it on .net 5.0 and it work Program.cs .,需要在 .net 核心 3.1 或更低版本中运行的所有应用程序中,我在 .net 5.0 上测试没有它并且它工作

    public class Program
    {
        public static void Main(string[] args)
        {
            AppContext.SetSwitch("Microsoft.AspNetCore.Routing.UseCorrectCatchAllBehavior", true);
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

Blazor Blazor

@page "/"
@page "/index/{*Path}"

<h1>Hello, world!</h1>
<h1>Path is @Path</h1>

@code
{
    [Parameter]
    public string Path { get; set; }

    protected override async Task OnParametersSetAsync()
    {
         await base.OnParametersSetAsync();
        Console.WriteLine($"Path is: {Path}");
    }
}

On apis, it would be:在 apis 上,它将是:

Controller: Controller:

  public class TestRouteController : Controller
    {
        [Route("/source/{*path}")]
        public string Invoke(string path)
        {

            Console.WriteLine(path);
            return path;
        }
    }

Result:结果:

Blazor: Blazor:

url: url:

Blazor 结果

result in browser console:导致浏览器控制台:

Blazor 结果

WebApi:网络接口:

url: url:

控制器结果

terminal:终端:

在此处输入图像描述

browser response:浏览器响应:

在此处输入图像描述

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

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