HttpClient 调用带有整数参数 Returns 的 web api 方法错误 404

HttpClient call to web api method with integer parameter Returns error 404

我真的看不出我做错了什么。我正在尝试调用一个 asp.net 核心网络 api 方法,该方法通过 HttpClient 接受一个整数,但它 returns 一个 404 错误。

HospitalController(网络 API)

[HttpGet("{id}")]
[Route("GetById")]
public JsonResult Get(int id)
{
    return Json(_hospitalService.Get(id));
}

HospitalController (MVC)

protected string url = "http://localhost:5001/api/Hospital";

[HttpGet]
public async Task<IActionResult> Edit(int id)
{
    if (id.Equals(0))
        return StatusCode(404);

    var accessToken = await HttpContext.GetTokenAsync("access_token");
    client.SetBearerToken(accessToken);
    HttpResponseMessage responseMessage = await client.GetAsync(url + "/GetById/" + id); //returns 404 error here.
    if (responseMessage.IsSuccessStatusCode)
    {
        var responseData = responseMessage.Content.ReadAsStringAsync().Result;

        var hospital = JsonConvert.DeserializeObject<Hospital>(responseData);
        var hospitalVM = Mapper.Map<HospitalViewModel>(hospital);
        return View(hospitalVM);
    }

    return View("Error");
}

我在 MVC 的同一个控制器中有一个 POST 方法可以工作。但是这个 GET 方法 returns 一个 404,我似乎不知道为什么。

根据

,api 中使用了两个路由模板
[HttpGet("{id}")] //Matches GET api/Hospital/5
[Route("GetById")] //Matches GET api/Hospital/GetById

两者都不符合正在调用的内容

http://localhost:5001/api/Hospital/GetById/5

Http{Verb} 属性通常用于 RestFul API。

When building a REST API, it's rare that you will want to use [Route(...)] on an action method. It's better to use the more specific Http*Verb*Attributes to be precise about what your API supports. Clients of REST APIs are expected to know what paths and HTTP verbs map to specific logical operations.

引用Routing to Controller Actions

更新网络上的路线模板api以映射到所需的路线

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

    //...code removed for brevity

    //Matches GET api/Hospital/GetById/5
    [HttpGet("GetById/{id:int}")]
    public IActionResult Get(int id) {
        return Ok(_hospitalService.Get(id));
    }
}

此外,HttpClient 旨在异步使用,因此 MVC 控制器也需要重构,因为混合阻塞调用 .Result 会导致死锁

protected string url = "http://localhost:5001/api/Hospital";

[HttpGet]
public async Task<IActionResult> Edit(int id) {
    if (id.Equals(0))
        return StatusCode(404);

    var accessToken = await HttpContext.GetTokenAsync("access_token");
    client.SetBearerToken(accessToken);
    HttpResponseMessage responseMessage = await client.GetAsync(url + "/GetById/" + id);
    if (responseMessage.IsSuccessStatusCode) {
        var responseData = await responseMessage.Content.ReadAsStringAsync();
        var hospital = JsonConvert.DeserializeObject<Hospital>(responseData);
        var hospitalVM = Mapper.Map<HospitalViewModel>(hospital);
        return View(hospitalVM);
    }

    return View("Error");
}