编程语言
首页 > 编程语言> > c# – ASP.NET核心属性路由

c# – ASP.NET核心属性路由

作者:互联网

我正在将项目迁移到asp net core,但我无法配置这些路由,我使用属性来映射操作.

ASP.Net WebAPI2的代码

[Route("api/[controller]")]
public class SalesController : Controller
{
    // api/sales/1 -> ok
    [HttpGet]
    public HttpResponseMessage Get(int id)
    {
        // Logic
    }   

    // api/sales -> ok
    [HttpGet]
    public HttpResponseMessage Get([FromUri] PaginationHelper pagination)
    {
        // Logic
    }  

    // api/sales?me -> ok
    [ActionName("Get")]
    public HttpResponseMessage GetMe(bool? me)
    {
        // Logic
    }  
}

ASP.Net核心代码

在Startup.cs文件中设置app.UseMvc();

[Route("api/[controller]")]
public class SalesController : Controller
{
    // api/sales/1 -> ok
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        // Logic
    }   

    // api/sales -> don't work
    [HttpGet] // -> ???
    public IActionResult Get(PaginationHelper pagination)
    {
        // Logic
    }  

    // api/sales?me -> don't work
    [HttpGet] // -> ???
    public IActionResult GetMe(bool? me)
    {
        // Logic
    }  
}

解决方法:

新框架期望更明确地指示端点的意图.

[Route("api/[controller]")]
public class SalesController : Controller {

    [HttpGet("{id:int}")] // GET api/sales/1
    public IActionResult Get(int id) {
        // Logic
    }

    [HttpGet] // GET api/sales?page=1 assuming PaginationHelper has page property
    public IActionResult Get([FromQuery]PaginationHelper pagination) {
        // Logic
    } 

    [HttpGet] // GET api/sales?me=true
    public IActionResult GetMe(bool? me = false) {
        // Logic
    }  
}

参考Asp.Net Core: Model Binding

标签:c,asp-net-core,asp-net-core-2-0,asp-net-core-routing
来源: https://codeday.me/bug/20190622/1264063.html