使用整数参数调用Web api方法的HttpClient返回错误404

时间:2018-01-29 03:28:08

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

我真的看不出我在这里做错了什么。我试图调用一个asp.net核心web api方法,该方法通过HttpClient接受一个整数,但它返回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方法返回404,我似乎不知道为什么。

1 个答案:

答案 0 :(得分:2)

根据

,api中使用了两个路由模板
class Collect < ActiveRecord::Base
  belongs_to :product
  belongs_to :collection

  delegate :shop, to: :product
  delegate :shopify_product_id, to: :product 
  delegate :shopify_collection_id, to: :collection 
end

class Collection < ActiveRecord::Base
  # verify all items belong to shop
  belongs_to :shop #verify
  has_many :collects, dependent: :destroy
  has_many :products, through: :collects

end

class Product < ActiveRecord::Base
  belongs_to :shop
  has_many :variants, ->{ order(:created_at) }, dependent: :destroy
  has_many :price_tests, dependent: :destroy
  has_many :metrics, ->{ order(:created_at) }, dependent: :destroy 
  has_many :collects, dependent: :destroy
  has_many :collections, through: :collects

两者都不匹配所谓的

[HttpGet("{id}")] //Matches GET api/Hospital/5
[Route("GetById")] //Matches GET api/Hospital/GetById

http://localhost:5001/api/Hospital/GetById/5 属性通常用于RestFul API。

  

在构建REST API时,您很少需要在操作方法上使用Http{Verb}。最好使用更具体的[Route(...)]来准确了解您的API支持的内容。 REST API的客户端应该知道哪些路径和HTTP谓词映射到特定的逻辑操作。

参考Routing to Controller Actions

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

Http*Verb*Attributes

HttpClient也是异步使用的,因此MVC控制器也需要重构,因为混合阻塞调用[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)); } } 会导致死锁

.Result