c# - 如何在 net core 3 中拥有一个具有前缀路由的基本控制器
问题描述
实际上我正在使用.NET Core 3,
我有这样一条路线的控制器:
[ApiController]
[Route("customers/app")]
public class CustomerAppController : ControllerBase
{
}
我想做的是拥有一个基本控制器,我可以在其中为所有控制器放置许多我想要的东西,包括路由前缀,如下所示:
[Route("api/v1/[controller]")]
public class CoreController : ControllerBase
{
protected virtual Object HandleException(Exception ex, string path, ILogger logger)
{
logger.LogError(ex, "Unhandled exception.");
return StatusCode(5000, new { ex.Message });
}
}
那么控制器将是:
[ApiController]
[Route("customers/app")]
public class CustomerAppController : CoreController
{
//TODO: put actions here
public override Object HandleException(Exception ex, string path, ILogger logger) { }
}
我怎样才能使这项工作?
我发现我可以使用这种方法:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UsePathBase("/api/v1");
//other things
}
现在我可以使用 api 调用我的 api localhost/api/v1/randompath
,但如果我使用它也可以使用localhost/randompath
解决方案
将 Route attr 添加到您的控制器并在那里设置路径。
[Route("api/v1/[controller]")]
[ApiController]
在您各自的控制器中。我正在使用.net core web api,它通过这种方法对我有用,而不必使用 app.UsePathBase()。如果我将路径设置为 /api/v1/ 我无法通过 url 模式 /api/[Controller] 访问 api 而无需补充 v1。
推荐阅读
- maven - 如何配置 Android Studio 以在项目中包含包含 pom.xml 的配置文件夹?
- function - 如何将字符串数组传递给函数并在 SQL 的“IN”语句中使用它
- python - 数据框唯一项目和 xy 位置到室友(共享位置)项目网格
- angular - Angular 9 ngx-image-cropper 使用滑块调整裁剪器大小
- java - 将字符串转换为键值对并在java中将其转换为一行
- python - 如何为误差线分配颜色?[Matplotlib]
- laravel - 如何使用 Laravel 进行多用户进程?
- css - 为什么我的 Angular 应用程序没有拿起可动手做的 CSS?
- c# - 从没有外部 SMTP 的 C# WPF 应用程序发送电子邮件
- image - 复制带有图像的幻灯片 python pptx