简体   繁体   English

ASP.NET Core 路由空参数

[英]ASP.NET Core routing empty parameters

I have controller with one method.我有一种方法的控制器。 Routing covers next scenarious:路由涵盖下一个场景:

1. userId="1" ,userEmail=null https://localhost:44371/api/customers/1
1. userId="1" ,userEmail="1" https://localhost:44371/api/customers/1/1

The main question how to send request when userId=null , userEmail="1" .主要问题是如何在userId=null , userEmail="1"时发送请求。 Use %20 and request something like https://localhost:44371/api/customers/%20/1 ?使用%20并请求类似https://localhost:44371/api/customers/%20/1 What is right way?什么是正确的方法?

[HttpGet("{userId}")]
[HttpGet("{userId}/{userEmail}")]
[ApiController]
public class CustomersController : ControllerBase
{
    public JsonResult GetCustomer(string userId, string userEmail)
    {
        return new JsonResult(string.Format("userId: {0}, email: {1} ", userId, userEmail));
    }
}

You are routing in wrong way so change your code to this because you will need to routing in the action method您以错误的方式路由,因此将代码更改为此,因为您需要在操作方法中进行路由

[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    [HttpGet("{userId}/{userEmail}")]
    public JsonResult GetCustomer(string userId, string userEmail)
    {
        return new JsonResult(string.Format("userId: {0}, email: {1} ", userId, userEmail));
    }
}

So you can request api like this所以你可以像这样请求api

https://localhost:44371/api/customers/1

Another example另一个例子

[Route("[controller]/[action]")]
public class ProductsController : Controller
{
    [HttpGet] // Matches '/Products/List'
    public IActionResult List() {
        // ...
    }

    [HttpGet("{id}")] // Matches '/Products/Edit/{id}'
    public IActionResult Edit(int id) {
        // ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM