我可以用 web api 控制器的传统路由模式替换属性路由吗?

我可以用 web api 控制器的传统路由模式替换属性路由吗?

问题描述:

我有 web api ValuesController(用 [ApiController] 标记)和里面的方法 [HttpPost] GetValue.

I have web api ValuesController (marked with [ApiController]) and the method [HttpPost] GetValue inside.

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public IEnumerable<string> GetValue()
    {
        return new string[] { "value1", "value2" };
    }
}

我修改了 Startup.cs

I have modifeid e Startup.cs

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllerRoute("default", "{controller}/{action}"); // added
        });

现在我希望方法的路由应该是 /api/Values/GetValue 当它是 /api/Values - 意味着 {action} 被忽略?

Now I expect that route to the method should be /api/Values/GetValue when it is the /api/Values - means the {action} is ignored?

是否可以将默认路由配置为在 uri 中包含 {action}?现在我强制使用 [HttpGet(nameof(GetValue))] 属性来定义动作,看起来很冗长.

Can the default routing be configured to include {action} to the uri? Now I'm forcing to attribute actions with the [HttpGet(nameof(GetValue))] what look verbose.

我知道标有 ApiController 的控制器是特定的东西,但它应该反应"吗?到 MapControllerRoute ?我在文档中找不到它.

I understand that controller marked with ApiController is specific thing, but should it "react" to the MapControllerRoute ? I can't find it in the documentation.

属性路由总是比默认路由具有更高的优先级.所以如果你想在默认情况下拥有/api/Values/GetValue 你可以改变控制器属性

Attribute route always has a higher priority then a default route. So if you want to have /api/Values/GetValue by default you can change controller attribute

[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase

或者如果你想使用默认启动路由,你必须从控制器中删除属性路由并修复你的默认路由:

Or if you want to use default route of startup, you have to remove attribute routing from the controller and fix your default route:

endpoints.MapControllerRoute("default", "api/{controller}/{action}");