需要帮助调用Web Api控制器方法来检索数据

时间:2017-04-18 21:41:01

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

我是Web Api的新手(我可能在这里错过了一些非常简单的内容)我有一个{A}项的Web Api项目,其属性类型let commands = [ { "user": "Rusty", "user_id": "83738373", "command_name": "TestCommand", "command_reply": "TestReply" }, { "user": "Rusty", "user_id": "83738373", "command_name": "SecondCommand", "command_reply": "TestReply" }, { "user": "Rusty", "user_id": "83738373", "command_name": "ThirdCommand", "command_reply": "TestReply" }, { "user": "Bart", "user_id": "83738233", "command_name": "ThirdCommand", "command_reply": "TestReply" }, { "user": "Rusty", "user_id": "83738373", "command_name": "FourthCommand", "command_reply": "TestReply" } ]; let userCommands = {}; commands.forEach(command=>{ if(!userCommands.hasOwnProperty(command.user_id)) userCommands[command.user_id] = 0; userCommands[command.user_id]++; }); // Then quickly check if they have too many commands if(userCommands["83738373"] > 3){ console.log("Too many!"); }和我只想在浏览器中调用Api,例如ProductsController.csList<Product>,以检索网址中指定ID的产品响应,但我无法检索任何数据。我找不到&#39;没找到&#39;每次都错误。我错过了什么使它找到数据并检索响应?

我尝试了以下内容:

localhost/api/products/1

甚至还没有找到以下内容:

/api/products/getproduct/1

1 个答案:

答案 0 :(得分:3)

确保路由配置正确

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

从那里你有两个选择路由到行动。

公约为主。

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