从MADS提供的关于控制器路由的部分(
see here - customise routes
)
名称空间路由约定.cs
public class NamespaceRoutingConvention : IControllerModelConvention
{
private readonly string _baseNamespace;
public NamespaceRoutingConvention(string baseNamespace)
{
_baseNamespace = baseNamespace;
}
public void Apply(ControllerModel controller)
{
var hasRouteAttributes = controller.Selectors.Any(selector =>
selector.AttributeRouteModel != null);
if (hasRouteAttributes)
{
// This controller manually defined some routes, so treat this
// as an override and not apply the convention here.
return;
}
// Use the namespace and controller name to infer a route for the controller.
//
// Example:
//
// controller.ControllerTypeInfo -> "My.Application.Admin.UsersController"
// baseNamespace -> "My.Application"
//
// template => "Admin/[controller]"
//
// This makes your routes roughly line up with the folder structure of your project.
//
if (controller.ControllerType.Namespace == null)
return;
var template = new StringBuilder(GetControllerNamespace(controller.ControllerType.Namespace));
template.Replace('.', '/');
template.Append("/[controller]");
foreach (var selector in controller.Selectors)
{
selector.AttributeRouteModel = new AttributeRouteModel()
{
Template = template.ToString()
};
}
}
private string GetControllerNamespace(string controllerNamespace)
{
return controllerNamespace == _baseNamespace
? ""
: controllerNamespace.Substring(
_baseNamespace.Length + 1,
controllerNamespace.Length -
_baseNamespace.Length - 1);
}
}
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
options.Conventions.Add(new NamespaceRoutingConvention("Enter the route namespace of the api folder")))
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
API文件夹结构
在api文件夹下,我现在有以下结构:
/api
/Ploop
HelloController.cs
HelloController.cs
TestController.cs
样本控制器代码
因此每个控制器代码如下所示:
public class HelloController : ControllerBase
{
[HttpGet]
public JsonResult Index()
{
return new JsonResult(new
{
message = "hello from XXX controller"
});
}
[HttpGet("{id?}")]
public JsonResult Index(int? id)
{
return new JsonResult(new
{
message = "Hello from XXX controller with index",
id
});
}
}
呼叫控制器
因此,当我们调用每个控制器时,我们会在浏览器中得到以下输出:
api/ploop/hellocontroller.cs版本
http://localhost:51248/Ploop/Hello
{"message":"Hello from Ploop HelloController"}
http://localhost:51248/Ploop/Hello/12
{"message":"Hello from Ploop HelloController with index","id":12}
API/HelloController.cs标准
http://localhost:51248/Hello
{"message":"Hello from root HelloController"}
http://localhost:51248/Hello/12
{"message":"Hello from root HelloController with index","id":12}
API/测试控制器.cs
http://localhost:51248/Test
{"message":"Hello from TestController"}
http://localhost:51248/Test/12
{"message":"Hello from TestController with index","id":12}