“剃须刀页面”不需要任何AreaAttribute
,足以将它们放入Areas/MyArea/Pages
文件夹中,这足以启用路由/MyArea/MyPage
+ My Proj
+ Areas
+ MyArea
+ Pages
- MyPage.cshtml
但是如果我将API Controlller MyApi.cs
放到MyArea
文件夹中:
+ My Proj
+ Areas
+ MyArea
+ Pages
- MyApi.cs
然后我被迫“硬编码”区域名称
[Area("MyArea")] // !!! can't be missed
[Route("[area]/api/[action]")]
[Produces("application/json")]
[ApiController]
public class MyApiController : ControllerBase { // ...
由于运行时error Error: While processing template '[area]/api', a replacement value for the token 'area' could not be found. Available tokens: 'action, controller'. To use a '[' or ']' as a literal string in a route or within a constraint, use '[[' or ']]' instead.
没有Razor Pages如何工作以及如何在没有ApiController的情况下强制MyApiController-仅遵循Razor Pages约定(我想避免显式区域硬编码)?
P.S。对我来说,可以删除所有“ api”属性,不仅包括Area,还可以删除Produces,ApiController ...,因为我的api控制器的方法通过了ContentResult { Content = json, ContentType = "application/json" }
,实际上我不需要它们的功能。
P.P.S有趣的是,当PageModel
不包含时,Razor Pages GetArea()
包含ControllerBase
方法。看起来他们确定area
的机制不同。
这些选项不起作用:
routes.MapAreaRoute("Configuration", "Configuration", "Configuration/{controller}/{action}");
或
routes.MapRoute("Configuration", "Configuration/{controller}/{action}",
defaults: new { area = "Configuration" },
constraints: new { area = "Configuration" });
或
routes.MapRoute("Configuration", "Configuration/ConfigurationApi/{action}",
defaults: new { area = "Configuration", controller = "ConfigurationApi" },
constraints: new { area = "Configuration", controller = "ConfigurationApi" });