【问题标题】:.Net Core Web API.Net Core Web API
【发布时间】:2018-05-08 22:12:44
【问题描述】:

.NET Core 的新手。

我做错了什么?这是我的控制器

[Route("api/[controller]")]
public class customerController : Controller
{
    // GET: api/values
    //[HttpGet]
    //public IEnumerable<string> Get()
    //{
    //    return new string[] { "value1", "value2" };
    //}

    // GET api/values/5
    [HttpGet("{id}")]
    public customer Get(int id)
    {
        var repo = new customerRepository();
        return repo.GetCustomerOnPhone(id);
    }
}

我可以使用这个 URL 调用 API

http://localhost:51375/api/customer/8172858817

我在 GET 方法中打断点,但 Id 始终为零。我无法获得读取从 URL 传递的值的方法。

有什么建议吗?

【问题讨论】:

  • Max int is 2147483647 你的值太大了。改为long
  • 或者使用Guid作为Id的

标签: c# asp.net-core asp.net-core-webapi


【解决方案1】:

int MaxValue = 2147483647

您的值8172858817 太大。

要么使用较小的值,要么将参数更改为long

[HttpGet("{id:long}")]
public IActionResult Get(long id) {
    var repo = new customerRepository();
    customer model = repo.GetCustomerOnPhone(id);
    return Ok(model);
}

参考Routing in ASP.NET Core : Route Constraint Reference

【讨论】:

  • 这行得通。如果我将方法名称更改为 GetCustomerByPhone,我不会遇到断点。我使用的新 URL 是 localhost:51375/api/customer/GetCustomerByPhone/8172858817 。如果我只使用 GET 作为我的方法名称,我就可以达到断点。为什么会这样?
  • 您需要更新路由模板。 [HttpGet("GetCustomerByPhone/{id})"]
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
  • 2018-03-26
  • 2018-11-06
  • 2019-08-06
相关资源
最近更新 更多