ASP Core:如何在没有AreaAttribute的情况下为api控制器配置区域(或如何为Api控制器启用约定区域路由)?

时间:2019-01-26 15:10:21

标签: asp.net-core asp.net-core-webapi razor-pages asp.net-core-2.2

“剃须刀页面”不需要任何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.

,我不能错过/传递AreaAttribute

没有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" });

0 个答案:

没有答案