gpt4 book ai didi

c# - 需要帮助调用 Web Api Controller 方法来检索数据

转载 作者:行者123 更新时间:2023-11-30 21:41:20 24 4
gpt4 key购买 nike

我是 Web Api 的新手(我可能在这里遗漏了一些非常简单的东西)我有一个带有 ProductsController.cs 的 Web Api 项目具有 List<Product> 类型的属性我只是想在浏览器中调用 Api,例如 localhost/api/products/1/api/products/getproduct/1检索 url 中指定 ID 的产品响应,但我无法让它检索任何数据。我每次都会收到“未找到”错误。我缺少什么来让它找到数据并检索响应?

我尝试了以下方法:

public IHttpActionResult Get(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
else
{
return Ok(product);
}
}

甚至以下仍未找到的返回:

public string Get(int id)
{
return "product test";
}

最佳答案

确保路由配置正确

WebApiConfig.cs

public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Attribute routing.
config.MapHttpAttributeRoutes();

// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

从那里你有两个路由到 Action 的选项。

基于约定。

public class ProductsController : ApiController {

//...constructor code removed for brevity

[HttpGet] // Matches GET api/products
public IHttpActionResult GetAllProducts() {
return Ok(products);
}

[HttpGet] // Matches GET api/products/1
public IHttpActionResult GetProduct(int id) {
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null) {
return NotFound();
}
return Ok(product);
}
}

或属性路由

[RoutePrefix("api/products")]
public class ProductsController : ApiController {

//...constructor code removed for brevity

[HttpGet]
[Route("")] // Matches GET api/products
public IHttpActionResult GetAllProducts() {
return Ok(products);
}

[HttpGet]
[Route("{id:int}")] // Matches GET api/products/1
public IHttpActionResult GetProduct(int id) {
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null) {
return NotFound();
}
return Ok(product);
}
}

关于c# - 需要帮助调用 Web Api Controller 方法来检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com