【问题标题】:ASP.NET Core 3 adding route prefixASP.NET Core 3 添加路由前缀
【发布时间】:2020-11-30 06:24:16
【问题描述】:

Startup.cs 中,我将api/ 添加到我的路线模式的开头。

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "api/{controller}/{action=Index}/{id?}");
});

但它什么也没做:旧的 URL 继续工作,以 /api 开头的 URL 返回 404。这没有任何意义!

如何让我的 API 在 /api 下提供服务?

【问题讨论】:

  • 用 [Route("api/[controller]")] 装饰你的控制器
  • 我不想这样做,因为有很多地方需要改变。真的应该设置一次。另外,我更喜欢使用常规路由而不是属性路由,因为我讨厌间接。
  • @Richard Barraclough 我还尝试了与您的代码相同的 "api/{controller}/{action=Index}/{id?}"),它可以按您的预期工作。也许您可以构建新的WebApplication 来测试或提供有关您的端点的更多详细信息。
  • 使用 Angular 模板创建了新的 ASP.NET Core Web 应用。它生成WeatherForecastController,可在/WeatherForecast 获得。将 api/ 添加到 endpoints.MapControllerRoute 之前,它仍然在 /WeatherForecastnot/api/WeatherForecast 上提供服务。

标签: asp.net-core asp.net-web-api asp.net-web-api-routing


【解决方案1】:

ASP.NET Core 3.0 中的全局路由前缀

创建自定义 MvcOptionsExtensions

    public static class MvcOptionsExtensions
    {
        public static void UseCentralRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute)
        {
            opts.Conventions.Insert(0, new RouteConvention(routeAttribute));
        }
    }

    public class RouteConvention : IApplicationModelConvention
    {
        private readonly AttributeRouteModel _centralPrefix;

        public RouteConvention(IRouteTemplateProvider routeTemplateProvider)
        {
            _centralPrefix = new AttributeRouteModel(routeTemplateProvider);
        }

        public void Apply(ApplicationModel application)
        {
            foreach (var controller in application.Controllers)
            {
                var matchedSelectors = controller.Selectors.Where(x => x.AttributeRouteModel != null).ToList();
                if (matchedSelectors.Any())
                {
                    foreach (var selectorModel in matchedSelectors)
                    {
                        selectorModel.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_centralPrefix,
                            selectorModel.AttributeRouteModel);
                    }
                }

                var unmatchedSelectors = controller.Selectors.Where(x => x.AttributeRouteModel == null).ToList();
                if (unmatchedSelectors.Any())
                {
                    foreach (var selectorModel in unmatchedSelectors)
                    {
                        selectorModel.AttributeRouteModel = _centralPrefix;
                    }
                }
            }
        }
    }

Startup.cs 中的代码

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews(opt => {
            opt.UseCentralRoutePrefix(new RouteAttribute("api"));
            ;
        });
    }

结果测试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多