我可以用 Web api 控制器的传统路由模式替换属性路由吗?
Can I replace the attribute routing with traditional route patterns for the web api controllers?
我有 web api ValuesController(标有 [ApiController]
)和里面的方法 [HttpPost] GetValue。
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public IEnumerable<string> GetValue()
{
return new string[] { "value1", "value2" };
}
}
我已经修改了Startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute("default", "{controller}/{action}"); // added
});
现在我希望方法的路由在 /api/Values
时应该是 /api/Values/GetValue
- 意味着 {action}
被忽略了吗?
可以将默认路由配置为将 {action} 包含到 uri 中吗?现在我强制使用 [HttpGet(nameof(GetValue))]
看起来冗长的内容来归因于动作。
我知道标有 ApiController 的控制器是特定的东西,但它应该对 MapControllerRoute 做出“反应”吗?我在文档中找不到它。
属性路由总是比默认路由具有更高的优先级。因此,如果你想默认使用 /api/Values/GetValue,你可以更改控制器属性
[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase
或者如果你想使用默认启动路由,你必须从控制器中删除属性路由并修复你的默认路由:
endpoints.MapControllerRoute("default", "api/{controller}/{action}");
我有 web api ValuesController(标有 [ApiController]
)和里面的方法 [HttpPost] GetValue。
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public IEnumerable<string> GetValue()
{
return new string[] { "value1", "value2" };
}
}
我已经修改了Startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute("default", "{controller}/{action}"); // added
});
现在我希望方法的路由在 /api/Values
时应该是 /api/Values/GetValue
- 意味着 {action}
被忽略了吗?
可以将默认路由配置为将 {action} 包含到 uri 中吗?现在我强制使用 [HttpGet(nameof(GetValue))]
看起来冗长的内容来归因于动作。
我知道标有 ApiController 的控制器是特定的东西,但它应该对 MapControllerRoute 做出“反应”吗?我在文档中找不到它。
属性路由总是比默认路由具有更高的优先级。因此,如果你想默认使用 /api/Values/GetValue,你可以更改控制器属性
[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase
或者如果你想使用默认启动路由,你必须从控制器中删除属性路由并修复你的默认路由:
endpoints.MapControllerRoute("default", "api/{controller}/{action}");