在单个根文件夹下组织WebApi控制器并路由到它们

时间:2018-09-09 19:30:01

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

背景

在大多数MVCWebApi应用程序中,我们通常看到以下结构:

/Controllers
  HomeController.cs
/Models

通常这是从MVC模板生成的。

然后将在Startup.cs中生成路由映射:

app.UseMvc(routes =>
{
    routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}");
});

增加了复杂性

当我们向Web应用程序添加其他部分(例如自定义ActionResults,Filters和Areas等)时,我们的Web应用程序的复杂性实际上开始增长。即使组织得井井有条,顶层文件夹也可能突然显得有些混乱。

问题

通常,当我们开箱即用地添加Area时,会创建一个名为Areas的新顶级文件夹。

我的喜好是将一个具有所有与控制器相关的功能的项目文件夹移动到其中,例如api文件夹。

例如:

/api
  /Home
    /Controllers
      HomeController.cs
    /Models
  /SomeArea1
    /Controllers
    /Models

现在的问题是,您需要更改路由配置,并在路由中包含api-我不要想要。

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "areaRoute",
        template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

是否可以在项目中具有上述文件夹结构,并有如下所示的路由?

http://localhost/ maps to /api/Home 
http://localhost/customer maps to /api/Customer

2 个答案:

答案 0 :(得分:0)

您可以按照以下代码进行路由

app.UseMvc(routes =>
{
   routes.MapRoute("blog", "blog/{*article}",
               defaults: new { controller = "Blog", action = "Article" });
   routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

请在此处查看文档

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.1#route-names

答案 1 :(得分:0)

Mads提供的有关控制器路由(see here - customise routes)的部分

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

Startup.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 / TestController.cs

http://localhost:51248/Test

{"message":"Hello from TestController"}

http://localhost:51248/Test/12

{"message":"Hello from TestController with index","id":12}