API Http get方法未调用

时间:2019-12-10 08:34:10

标签: c# asp.net-mvc api http http-get

我创建了如下简单的API:

public class TestController : ApiController { 
    [HttpGet, Route("ProductData")]
    public IHttpActionResult ProductData(int id) {
            try {
                List<Product> products = new List<Product>() {
                    new Product() { Name = "TestProduct", Id = "001", Quantity = "15-001" },
                    new Product() { Name = "TestProduct", Id = "002", Quantity = "15-002" },
                    new Product() { Name = "TestProduct", Id = "003", Quantity = "15-003" },
                    new Product() { Name = "TestProduct", Id = "004", Quantity = "15-004" },
                    new Product() { Name = "TestProduct", Id = "005", Quantity = "15-005" },
            };
                return Ok(products.Where(product => product.Id == id.ToString()).Select(product => product).FirstOrDefault());
            }
            catch {
                throw;
            }
        }
    }

我通过控制台使用此服务,如下所示:

HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("http://localhost:64672/");
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage getData = httpClient.GetAsync("api/Test/ProductData", 135).Result;

if (getProductData.IsSuccessStatusCode) {
    var message = postMessage.Content.ReadAsStringAsync().Result;

    Console.WriteLine(" Message from API : {0}", message.Replace(',', ' ').ToString());
}

但是我没有从API获得输出,而是IsSuccessStatusCode变成了false,请有人对此提供帮助

从浏览器调用时,出现此错误:

<Error> 
    <Message> No HTTP resource was found that matches the request URI 'localhost:64672/api/Test/ProductData?id=120'. 
    </Message> 
    <MessageDetail> No action was found on the controller 'IdsApp' that matches the name 'ProductData'. 
    </MessageDetail> 
</Error>

3 个答案:

答案 0 :(得分:3)

您仍然可以使用路由,但必须做些不同。

HttpResponseMessage getData = httpClient.GetAsync(string.Format("api/Test/ProductData?id={0}", 135)).Result;

答案 1 :(得分:2)

您应该在api控制器操作中使用int id属性装饰[FromRoute]。因此,将int id更改为[FromRoute]int id。并将Route("ProductData")更改为Route("ProductData/{id}")。最后,像这样修改GetAsync() uri:

var getData = httpClient.GetAsync($"api/Test/ProductData/{135}").Result;

答案 2 :(得分:2)

这与其他人所说的如何设置路由有关。

您需要确定是否要让URI看起来像

api/Test/ProductData?id={0}

api/Test/ProductData/{0}

我个人认为它作为第二个看起来更好,因为这样您就可以在其上链接其他路线

api/Test/ProductData/{productId}/store/{storeID}

在该示例中,从storeId的特定商店提取productId产品

一天结束时,您要根据自己的URI结构来选择个人偏好

如何设置第二个选项是这样更改方法上方的route属性:

[HttpGet]
[Route("ProductData/{id}")]
public IActionResult ProductData(int id)
{
 .....Whatever code
}

我个人不喜欢将所有属性放在相同的方括号中,但这只是我自己的代码编写风格。宁愿将属性分开,我只是觉得更容易阅读