.NET 配置全局路由前缀

文件目录

image.png

创建 RouteConvention

``` using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.Routing;

namespace Cari.Rescue.Web.Common { ///

/// 全局路由前缀配置 /// public class RouteConvention : IApplicationModelConvention { /// /// 定义一个路由前缀变量 /// private readonly AttributeRouteModel _centralPrefix; /// /// 调用时传入指定的路由前缀 /// /// public RouteConvention(IRouteTemplateProvider routeTemplateProvider) { _centralPrefix = new AttributeRouteModel(routeTemplateProvider); } /// /// 接口的Apply方法 /// /// public void Apply(ApplicationModel application) { //遍历所有的 Controller foreach (var controller in application.Controllers) { // 1、已经标记了 RouteAttribute 的 Controller //这一块需要注意,如果在控制器中已经标注有路由了,则会在路由的前面再添加指定的路由内容。

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);
                }
            }

            //2、 没有标记 RouteAttribute 的 Controller
            var unmatchedSelectors = controller.Selectors.Where(x => x.AttributeRouteModel == null).ToList();
            if (unmatchedSelectors.Any())
            {
                foreach (var selectorModel in unmatchedSelectors)
                {
                    // 添加一个 路由前缀
                    selectorModel.AttributeRouteModel = _centralPrefix;
                }
            }
        }
    }
}

} ```

创建 MvcOptionsExtensions

``` using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Cari.Rescue.Web.Common; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing;

namespace Router.Utility.Route { ///

/// 路由扩展 /// public static class MvcOptionsExtensions { /// /// 扩展方法 /// /// /// public static void UseCentralRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute) { // 添加我们自定义 实现IApplicationModelConvention的RouteConvention opts.Conventions.Insert(0, new RouteConvention(routeAttribute)); } } } ```

添加配置

builder .Services.AddControllers(option => { //设置路由全局前缀 api option.UseCentralRoutePrefix(new RouteAttribute("api/")); }) .AddJsonOptions(option => { // 解决中文乱码 option.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); }) ;

测试

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值