解决Web API路由配置支持Area及命名空间参数
2021-01-07 12:28
标签:解决 The web_api style compare binding 空间 select defaults 解决Web API路由配置支持Area及命名空间参数 首先创建一个新的HttpControllerSelector类 其次,在全局webApi配置文件中添加 最后,在区域在配置webApi路径 解决Web API路由配置支持Area及命名空间参数 标签:解决 The web_api style compare binding 空间 select defaults 原文地址:https://www.cnblogs.com/youguess/p/13155071.htmlusing System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
namespace _1_解决MVC的Controller和Web_API的Controller类名不能相同的问题.App_Start.webExt
{
public class NamespaceHttpControllerSelector : DefaultHttpControllerSelector
{
private const string NamespaceRouteVariableName = "namespaceName";
private readonly HttpConfiguration _configuration;
private readonly Lazy
//为了让WebApi也支持NameSpace
config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//是为了让WebApi的控制器自动匹配ApiController
var suffix = typeof(DefaultHttpControllerSelector).GetField("ControllerSuffix", BindingFlags.Static | BindingFlags.Public);
if (suffix != null) suffix.SetValue(null, "ApiController");
//为了让WebApi也支持NameSpace
config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
this.AreaName + "Api",
"api/" + this.AreaName + "/{controller}/{action}/{id}",
new
{
action = RouteParameter.Optional,
id = RouteParameter.Optional,
namespaceName = new string[] { string.Format("_1_解决MVC的Controller和Web_API的Controller类名不能相同的问题.Areas.{0}.Controllers", this.AreaName) }
},
null
//new { action = new StartWithConstraint() }
);
public class shopAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "shop";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"shop_default",
"shop/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new string [] { "_1_解决MVC的Controller和Web_API的Controller类名不能相同的问题.Areas.shop.Controllers" }
);
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
this.AreaName + "Api",
"api/" + this.AreaName + "/{controller}/{action}/{id}",
new
{
action = RouteParameter.Optional,
id = RouteParameter.Optional,
namespaceName = new string[] { string.Format("_1_解决MVC的Controller和Web_API的Controller类名不能相同的问题.Areas.{0}.Controllers", this.AreaName) }
},
null
//new { action = new StartWithConstraint() }
);
}
}
文章标题:解决Web API路由配置支持Area及命名空间参数
文章链接:http://soscw.com/index.php/essay/40699.html