.NET Core Web API

7

刚接触.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传递的值。

有什么建议吗?


最大整数是 2147483647。您的值太大了,请改用 long - Nkosi
或者使用 GUID 作为 ID。 - Antoshjke
1个回答

7

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);
}

参考 ASP.NET Core 中的路由:路由约束参考


这个可以工作。如果我将方法名称更改为GetCustomerByPhone,我就不会触发断点。我正在使用的新URL是http://localhost:51375/api/customer/GetCustomerByPhone/8172858817。如果我只使用GET作为我的方法名称,我就能够触发断点。为什么会这样? - Coder77
您需要更新路由模板。[HttpGet("GetCustomerByPhone/{id})"] - Nkosi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接