在ASP.NET API中如何在控制器之前为所有URL添加一个通用前缀?

huangapple go评论70阅读模式
英文:

How to prepend a common prefix to all URLs before the controller in ASP.NET API?

问题

我正在开发一个ASP.NET API项目,在这个项目中我有多个控制器,我想在控制器路由之前为所有的URL添加一个共同的前缀。例如,我希望所有的API端点都有前缀"/appapi/",然后是控制器名称。

我知道可以通过在每个控制器中手动添加前缀来实现这一点,使用[Route]属性,例如[Route("appapi/MyController")]。然而,这需要更新每个控制器,这可能会耗费大量时间并且容易出错。

是否有更高效和集中的方法,可以在不单独修改每个控制器的情况下,将这个共同前缀添加到所有的URL中?我希望避免在多个地方重复前缀,并且希望有一个单一的配置或设置,可以将其应用到所有的控制器中。

我正在使用ASP.NET 6.0,并且已经尝试在我的Program.cs文件的Configure方法中使用app.UsePathBase("/appapi"),但它没有按预期的方式添加前缀到URL中。

关于如何实现这一点的任何指导或建议将不胜感激。谢谢!

英文:

I'm working on an ASP.NET API project where I have multiple controllers, and I want to prepend a common prefix to all the URLs before the controller route. For example, I want all my API endpoints to have the prefix "/appapi/" followed by the controller name.

I know that I can achieve this by manually adding the prefix in each controller using the [Route]attribute, like [Route("appapi/MyController")]. However, this requires updating every controller, which can be time-consuming and error-prone.

Is there a more efficient and centralized way to add this common prefix to all the URLs without modifying each controller individually? I want to avoid duplicating the prefix in multiple places and have a single configuration or setup that applies it to all controllers.

I'm using ASP.NET 6.0 and have already tried using app.UsePathBase("/appapi") in the Configure method of my Program.cs file, but it didn't prepend the prefix to the URLs as expected.

Any guidance or suggestions on how to achieve this would be greatly appreciated. Thank you!


app.UseRouting();
app.UsePathBase("/appapi");

答案1

得分: 0

当然可以,实际上,使用 app.UsePathBase 可以实现这一目标。但根据您共享的代码片段和描述,似乎您的配置不正确。在 UsePathBase 中间件中,我们必须传递我们的新路由值,以便在所有现有控制器中设置全局路由前缀。

以下是正确的方法:

Program.cs:

app.UsePathBase(new PathString("/appapi"));
app.UseRouting();

app.Run();

注意: 正如您所看到的,我正在使用新的路由前缀传递前缀,而且您的控制器应该与您的控制器名称相同。

Demo Controller:

[Route("RoutePrefixTest")]
[ApiController]
public class RoutePrefixTestController : ControllerBase
{
    public IActionResult GetCity()
    {
        var checkBaseRoutePath = HttpContext.Request.PathBase;

        var cityList = new List<City>()
        {
            new City { Id = 101, Name = "Alberta" },
            new City { Id = 102, Name = "Toronto" },
            new City { Id = 103, Name = "British Comlombia" },
        };
        return Ok(cityList);
    }
}

Demo Model:

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
}

输出:

在ASP.NET API中如何在控制器之前为所有URL添加一个通用前缀?

在ASP.NET API中如何在控制器之前为所有URL添加一个通用前缀?

注意: 请参考官方文档

英文:

> Is there a more efficient and centralized way to add this common
> prefix to all the URLs without modifying each controller individually?
> I want to avoid duplicating the prefix in multiple places and have a
> single configuration or setup that applies it to all controllers.

Of course you can, in fact, using app.UsePathBase we can achieve that. But based on your shared code snippet and description it seems that, your configuration is not correct. Within UsePathBase middleware we have to pass our new route value in order to set a global route prefix with all the existing controller.

Here is the correct way:

Program.cs:

<!-- language: c# -->
app.UsePathBase(new PathString("/appapi"));
app.UseRouting();

app.Run();

Note: As you can see I am passing the prefix using new route prefix and also your controller should have route name as your controller only.

Demo Controller:

<!-- language: c# -->
[Route("RoutePrefixTest")]
[ApiController]
public class RoutePrefixTestController : ControllerBase
{
public IActionResult GetCity()
{
var checkBaseRoutePath = HttpContext.Request.PathBase;

            var cityList = new List&lt;City&gt;()
            {
                new City { Id = 101, Name = &quot;Alberta&quot; },
                new City { Id = 102, Name = &quot;Toronto&quot; },
                new City { Id = 103, Name = &quot;British Comlombia&quot; },
            };
            return Ok(cityList);
        }
    }

Demo Modeel:

<!-- language: c# -->
public class City
{
public int Id { get; set; }
public string Name { get; set; }
}

Output:

在ASP.NET API中如何在控制器之前为所有URL添加一个通用前缀?

在ASP.NET API中如何在控制器之前为所有URL添加一个通用前缀?

Note: Please refer to the official document here.

huangapple
  • 本文由 发表于 2023年6月29日 22:08:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76581827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定