结构:
+ MyProj
+ Areas
+ Configuration
- Pages
- ConfigurationApiController.cs
VS2017提出了创建不带Controllers文件夹的控制器的方法,这对我来说还可以,因为我使用Razor Pages并且不需要Controllers文件夹:
不起作用:
定义的控制器:
[Route("api")]
[Produces("application/json")]
[ApiController]
public class ConfigurationApiController : ControllerBase
{
private readonly ApplicationSettings applicationSettings;
[HttpGet]
public ActionResult GetUsers()
{
Mvc路由配置的标准方式:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
如何路由到GetUsers
的{{1}}操作?
答案 0 :(得分:5)
修改api路由并添加区域属性以提供[area]路由的区域名称。
[Area("Configuration")]
[Route("[area]/api/[controller]")]
[ApiController]
public class ConfigurationApiController : ControllerBase
{
}
仅此而已,可以在http://localhost:8080/Configuration/api/ConfigurationApi上访问它
答案 1 :(得分:2)
其他一些路由选项:
工作选项:http://localhost:8080/api(是,没有任何操作)
删除Web API属性后
// [Route("api")]
// [Produces("application/json")]
// [ApiController]
然后http://localhost:8080/ConfigurationApi/GetUsers
可以,但是路由中没有区域,并且“按惯例路由至该区域”似乎不起作用,是asp核心: ASP Core: how to configure area for api controller without AreaAttribute (or how to enable convention area routing for Api controller)? 和https://github.com/aspnet/AspNetCore/issues/7042
在这种情况下也应返回ContentResult { Content = json, ContentType = "application/json" }
,但这对我来说是可以的,因为我更喜欢使用就地序列化而不是流序列化器。
[Area("Configuration")]
[Route("[area]/api")]
[Produces("application/json")]
[ApiController]
其他选项:[Route(“ [area] / api / [action]”)]路由至http://localhost:8080/Configuration/api/GetUsers
删除区域属性时引发运行时错误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.
//[Area("Configuration")]
[Route("[area]/api")]
[Produces("application/json")]
[ApiController]