调用 WebApi 时出错

Getting error while calling WebApi

我正在尝试创建一个 API 并尝试通过 chrome 访问它,希望它进入 return 项目列表

public class ProductController : ApiController
{
    Product product = new Product();
    List<Product> productList = new List<Product>();

    [HttpGet]
    public HttpResponseMessage GetTheProduct(int id)
    {
        this.productList.Add(new Product {Id = 111,Name= "sandeep" });
        return Request.CreateResponse(HttpStatusCode.OK, this.productList.FirstOrDefault(p => p.Id == 111));
    }
}

我没有添加路由所以想 运行 它使用默认路由但是当我 运行 设置它时,我得到

No HTTP resource was found that matches the request URI 'http://localhost:65098/api/GetTheProduct()'. No type was found that matches the controller named 'GetTheProduct()'.

建议我需要什么才能让它工作。

如果使用默认路由,则配置可能如下所示

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {

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

这意味着路由使用基于约定的路由和以下路由模板"api/{controller}/{id}"

您当前状态下的控制器不符合约定。这会导致请求在路由表中不匹配,从而导致遇到“未找到”问题。

重构控制器以遵循约定

public class ProductsController : ApiController {
    List<Product> productList = new List<Product>();

    public ProductsController() {
        this.productList.Add(new Product { Id = 111, Name = "sandeep 1" });
        this.productList.Add(new Product { Id = 112, Name = "sandeep 2" });
        this.productList.Add(new Product { Id = 113, Name = "sandeep 3" });
    }

    //Matched GET api/products
    [HttpGet]
    public IHttpActionResult Get() {
        return Ok(productList);
    }

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

最后基于配置的路由模板,然后控制器期望一个看起来像

的请求
http://localhost:65098/api/products/111.

获取与提供的 id 匹配的单个产品(如果存在)。

参考Routing in ASP.NET Web API