简体   繁体   中英

Need help calling Web Api controller methods to retrieve data

I'm new to Web Api (I'm probably missing something very straightforward here) I have a Web Api project with ProductsController.cs that has a property of type List<Product> and I simply want to call the Api in the browser eg localhost/api/products/1 or /api/products/getproduct/1 to retrieve the product response for the specified Id in the url but I cannot get it to retrieve any data. I get a 'not found' error each time. What am I missing to make it find the data and retrieve the response?

I have tried the following:

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

And even the following which still returns not found:

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

Make sure the the routing is configured properly

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

From there you have two options of routing to the action.

Convention-based.

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

or Attribute routing

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM