【问题标题】:Getting error while calling WebApi调用 WebApi 时出错
【发布时间】:2018-12-04 22:14:46
【问题描述】:

我正在尝试创建一个 API 并尝试通过 chrome 访问它,期望它返回项目列表

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));
    }
}

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

没有找到与请求匹配的 HTTP 资源 URI 'http://localhost:65098/api/GetTheProduct()'。 找不到与名为的控制器匹配的类型 'GetTheProduct()'。

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

【问题讨论】:

标签: c# asp.net-web-api asp.net-web-api-routing


【解决方案1】:

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

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}"

您当前状态的控制器未遵循约定。这会导致请求在路由表中不匹配,从而导致出现 Not Found 问题。

重构控制器以遵循约定

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

【讨论】:

  • 谢谢亲爱的,我正在寻找同样的解释
猜你喜欢
  • 1970-01-01
  • 2019-11-21
  • 2021-06-29
  • 2023-03-15
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
相关资源
最近更新 更多