如何在ASP.NET Core 2.0 MVC中为GET和POST请求添加单独的默认路由?

5 c# asp.net-core-mvc asp.net-core asp.net-core-2.0

目前,我的Startup.cs类中包含以下内容:

app.UseMvc(routes =>
    {
        routes.MapRoute("default", "api/{controller}/{action=Get}");
    });
Run Code Online (Sandbox Code Playgroud)

我所有的MVC控制器在其上都有一个Get方法,其中许多控制器还具有一个Post。像这样:

public class ExampleController : Controller
{
    [HttpGet]
    public MyType Get()
    {
        return GetMyTypeFromSomewhere();
    }

    [HttpPost("api/[controller]")]
    public void Post([FromBody]MyType updated)
    {
        //do some stuff with the new instance
    }
}
Run Code Online (Sandbox Code Playgroud)

目前,我需要("api/[controller]")使用Post方法,以便发布请求能够到达它。

我希望能够将其删除,并默认将POST请求重定向到控制器的Post方法。问题是,如果我在当前状态下这样做,HTTP POST请求将最终发布到/api/Example/Get

我研究了MapGetMapPost,但是这些方法的唯一实现是可以使管道短路,在传递的RequestDelegate中进行处理和响应。我的控制器方法从未达到过这种方式。

我该如何实现?

编辑

可能值得添加,有些控制器上有额外的GET和POST方法,这些方法可以在处到达api/controller/action,这意味着我需要在{action}某处指定路由。但是,这样做意味着不再只能通过控制器名称访问默认的Get和Post方法,因此将其添加=Get为MapRoute中的默认操作。

Dav*_*ang 3

当然,每个请求都会使用该Get方法,因为您告诉它默认为:

routes.MapRoute("default", "api/{controller}/{action=Get}");
Run Code Online (Sandbox Code Playgroud)

如果您指定文字段(操作标记),即 ,/api/example/getMVC 会将其视为优先顺序中的最顶层。这就是为什么它总是Get在控制器内选择操作,因为您也在 url 中指定了操作令牌。

不要使用 Web api 这样做!

相反,Web api 使用HttpVerb来映射路线。HttpVerb所以您不应该与 Url 一起指定。您可以将HttpVerb方法类型与请求一起提供。

将 api 路由视为标识资源/资源集合。这与您对 MVC(RPC 风格)的看法不同。

更改为这些并尝试一下:

启动.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvcWithDefaultRoute();
}
Run Code Online (Sandbox Code Playgroud)

客户资源

[Route("api/[controller]")]
public class CustomersController : Controller 
{
    [HttpGet]
    public IActionResult Get()
    {   ...   }

    [HttpPost]
    public IActionResult Post()
    {   ...   }
}
Run Code Online (Sandbox Code Playgroud)