在 ASP.NET MVC 中设置备用控制器文件夹位置

发布于 2024-10-06 05:18:32 字数 279 浏览 6 评论 0原文

我们可以使用 HTML 视图的默认文件夹约定的 MVC 应用程序,但我们希望设置备用“Services”文件夹,其中的控制器仅用于返回 xml 或 json 的 Web 服务。

因此,路由“/Services/Tasks/List”将被路由到“/Services/TaskService.cs”,而“/Tasks/List”将被路由到标准“/Controllers/TaskController.cs”,

我们希望将服务控制器与视图控制器分开。我们认为区域或使用其他项目不会起作用。解决这个问题的最佳方法是什么?

We can an MVC app that uses the default folder conventions for the HTML views, but we'd like to set up alternate "Services" folder with controllers used only for web services returning xml or json.

So the route "/Services/Tasks/List" would be routed to "/Services/TaskService.cs", while "/Tasks/List" would be routed to the standard "/Controllers/TaskController.cs"

We'd like to keep the service controllers separate from the view controllers. We don't think areas or using another project will work. What would be the best way to approach this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

演出会有结束 2024-10-13 05:18:32

您可以使用路由来完成此操作,并将控制器保留在单独的命名空间中。
MapRoute 允许您指定哪个名称空间对应于路由。

示例

给定此控制器

namespace CustomControllerFactory.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
           return new ContentResult("Controllers");
        }
    }
}

namespace CustomControllerFactory.ServiceControllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
           return new ContentResult("ServiceControllers");
        }
    }
}

和以下路由,

 routes.MapRoute(
           "Services",
           "Services/{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new string[] { "CustomControllerFactory.ServiceControllers" } // Namespace
        );


        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new string[] { "CustomControllerFactory.Controllers"} // Namespace
        );

您应该期待以下响应

/Services/Home

<块引用>

服务控制器

/主页

<块引用>

控制器

You can do this using Routing, and keeping the controllers in separate namespaces.
MapRoute lets you specify which namespace corresponds to a route.

Example

Given this controllers

namespace CustomControllerFactory.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
           return new ContentResult("Controllers");
        }
    }
}

namespace CustomControllerFactory.ServiceControllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
           return new ContentResult("ServiceControllers");
        }
    }
}

And the following routing

 routes.MapRoute(
           "Services",
           "Services/{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new string[] { "CustomControllerFactory.ServiceControllers" } // Namespace
        );


        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new string[] { "CustomControllerFactory.Controllers"} // Namespace
        );

You should expect the following responses

/Services/Home

ServiceController

/Home

Controllers

被翻牌 2024-10-13 05:18:32

在Asp.Net Core中:我使​​用AreaFeature库ServiceCollectionExtensions

首先设置你的中间件;

    services.AddMvc(options => 
        options.EnableEndpointRouting = false).
        AddFeatureFolders().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Latest);

在扩展中:

return AddFeatureFolders(services, new FeatureFolderOptions());

根据您的要求实现:

 public static IMvcBuilder AddFeatureFolders(this IMvcBuilder services, FeatureFolderOptions options)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            if (options == null)
                throw new ArgumentException(nameof(options));

            var expander = new FeatureViewLocationExpander(options);

            services.AddMvcOptions(o => o.Conventions.Add(new FeatureControllerModelConvention(options)))
                .AddRazorOptions(o =>
                {
                    o.ViewLocationFormats.Clear();
                    o.ViewLocationFormats.Add(options.FeatureNamePlaceholder + @"\{0}.cshtml");
                    o.ViewLocationFormats.Add(options.FeatureNamePlaceholder + @"\_Views\{0}.cshtml");
                    o.ViewLocationFormats.Add(options.FeatureFolderName + @"\Shared\{0}.cshtml");
                    o.ViewLocationFormats.Add(options.DefaultViewLocation);

                    o.ViewLocationExpanders.Add(expander);
                });

            return services;
        }

在我的情况下,我更喜欢一个单独的 _View 文件夹来存放像这样的功能文件夹中的视图

~/Features/Account/_Views/login.cshtml
~/Features/Account/AccountController.cs
~/Features/Account/AccountModel.cs

In Asp.Net Core: I used AreaFeature library ServiceCollectionExtensions

First set your middleware;

    services.AddMvc(options => 
        options.EnableEndpointRouting = false).
        AddFeatureFolders().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Latest);

In the extenssion:

return AddFeatureFolders(services, new FeatureFolderOptions());

implement as according your requirement:

 public static IMvcBuilder AddFeatureFolders(this IMvcBuilder services, FeatureFolderOptions options)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            if (options == null)
                throw new ArgumentException(nameof(options));

            var expander = new FeatureViewLocationExpander(options);

            services.AddMvcOptions(o => o.Conventions.Add(new FeatureControllerModelConvention(options)))
                .AddRazorOptions(o =>
                {
                    o.ViewLocationFormats.Clear();
                    o.ViewLocationFormats.Add(options.FeatureNamePlaceholder + @"\{0}.cshtml");
                    o.ViewLocationFormats.Add(options.FeatureNamePlaceholder + @"\_Views\{0}.cshtml");
                    o.ViewLocationFormats.Add(options.FeatureFolderName + @"\Shared\{0}.cshtml");
                    o.ViewLocationFormats.Add(options.DefaultViewLocation);

                    o.ViewLocationExpanders.Add(expander);
                });

            return services;
        }

In my case i preferred a separated _View folder for views in the features folders like that

~/Features/Account/_Views/login.cshtml
~/Features/Account/AccountController.cs
~/Features/Account/AccountModel.cs
無處可尋 2024-10-13 05:18:32

您需要创建自己的控制器工厂来实现 IControllerFactory。

查看 http://nayyeri.net/custom-controller-factory-in -asp-net-mvc 为例。

You'll want to create your own controller factory implementing IControllerFactory.

Check out http://nayyeri.net/custom-controller-factory-in-asp-net-mvc for an example.

情深如许 2024-10-13 05:18:32

如果您看到黄色文件夹名称
在root中添加文件夹名称

后,您必须修改routes.MapRoute为“App_Start&gt; RouteConfig”

修改默认路由

routes.MapRoute(
          "Default",
          "{controller}/{action}/{id}",
          new { controller = "Home", action = "Index", id =     UrlParameter.Optional },
          new string[] { "mvcPartialView.HomeController" } // Namespace 
      );

并添加此

routes.MapRoute(
       "ApiControllerOne", // Name of folder
       "ApiControllerOne/{controller}/{action}/{id}",
        new { controller = "ApiFactory", action = "callFactoryOne", id = UrlParameter.Optional },
        new string[] { "mvcPartialView.ApiControllerOne" } // Namespace
    );

If you see yellow folder names
Add folder Name in root

After, you have to modify routes.MapRoute into "App_Start > RouteConfig"

Modify Default route

routes.MapRoute(
          "Default",
          "{controller}/{action}/{id}",
          new { controller = "Home", action = "Index", id =     UrlParameter.Optional },
          new string[] { "mvcPartialView.HomeController" } // Namespace 
      );

and Add this

routes.MapRoute(
       "ApiControllerOne", // Name of folder
       "ApiControllerOne/{controller}/{action}/{id}",
        new { controller = "ApiFactory", action = "callFactoryOne", id = UrlParameter.Optional },
        new string[] { "mvcPartialView.ApiControllerOne" } // Namespace
    );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文