gpt4 book ai didi

c# - 使用区域和 Controller 名称进行路由(asp.net core)

转载 作者:行者123 更新时间:2023-11-30 20:29:01 25 4
gpt4 key购买 nike

为了防止我的应用程序变得困惑,我开始使用区域。但现在我总是要打电话:
http://localhost:49358/Document/Document/
而不是:
http://localhost:49358/Document/
如何更改我的路线以按区域名称访问 Controller ?(没有家庭 Controller )

我的项目中有以下文件夹结构:

Folderstructure inside my Project
我到区域的路线代码如下所示:

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

然后我将 [Area("Document")] 标签放在我的 DocumentController 中。

编辑:
正如 Shyju 和 Jamie Taylor 所建议的那样,我选择了 HomeControllers。 (感谢你们的快速回答和解释)

我的结构现在看起来像这样并且路由按预期工作:
enter image description here

对我来说,拥有这么多 HomeControllers 和 Index Files 还是有点失望。导航代码不再那么容易:
enter image description here

编辑2:
在对所有这些 Homecontroller 感到非常恼火之后,我采用了 Jamie Taylor 建议的解决方案,并将所有内容重新排列在 Features 文件夹中。它需要更多的配置,但在我看来更简洁。
这篇 Microsoft 文章中也对此进行了进一步解释(只是跳过区域内容):
https://msdn.microsoft.com/en-us/magazine/mt763233.aspx

我的结构现在看起来像这样,路由工作起来很有魅力, Controller 名称仍然有意义:
enter image description here

最佳答案

我不确定这就是 areas 的用途。也许您应该重新考虑您的架构。

在我的ASP.NET MVC Core application template ,我利用了功能文件夹,它的工作方式有点像区域。

为此,我将以下内容添加到 ConfigureServices 方法中:

serviceCollection.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new FeatureLocationExpander());
});

FeatureLocationExpander 是:

public class FeatureLocationExpander : IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext context)
{
// Don't need anything here, but required by the interface
}

public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
// The old locations are /Views/{1}/{0}.cshtml and /Views/Shared/{0}.cshtml
// where {1} is the controller and {0} is the name of the View

// Replace /Views with /Features
return new string[]
{
"/Api/{1}/{0}.cshtml",
"/Features/{1}/{0}.cshtml",
"/Features/Shared/{0}.cshtml"
};
}
}

替换由 ExpandViewLocations 为您的区域返回的新字符串 [] 的内容意味着您不必添加路由属性。

但是,这不能解决您的问题,因为这不是 areas 的用途。

除非您在 Documents 区域下添加了一个 razor 页面(名为 Index.cshtml)作为 Documents 区域的索引页面。这个 Index.cshtml 可以在你的/Documents/Documents/Index.cshtml 中提供 Index.cshtml 的所有功能,还有一个额外的好处是有一个像你的 Controller 一样的代码隐藏文件(还记得 ASP.NET webforms 吗?) .

关于c# - 使用区域和 Controller 名称进行路由(asp.net core),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com