locked
web api calling wrongly RRS feed

  • Question

  • User81789783 posted

    i have written web api and called it using index.html ,its working fine

    • get all products
    • get by name
    • get by id

    now i installed postman (rest client) but it working fine  for first method only i.e  get all products ,but when i called it for get by id

    http://localhost:6869/api/products?id=2 it always return first record

    Similarly if i called for get by name http://localhost:6869/api/products?name=Hammer it always return first record

    that means its all good till i checked all methods in Visual studio but in post man its not working fine

    [Route("api/products/{id:int}")]
            public IHttpActionResult GetProductByid(int id)
            {
    
                var product = products.FirstOrDefault((p) => p.Id == id);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
        [Route("api/products/{name}")]
          
            public IEnumerable<Product> GetProductByName(string name)
            {
                //if (string.IsNullOrWhiteSpace(name))
                //{
                //    return BadRequest("name is empty");
                //}
                var product = products.Where(p => p.Name == name).ToList();
                return product;
             //   return Ok(products);
            }
      [Route("api/products")]
            public IEnumerable<Product> GetAllProducts()
            {
    
                return products;
            }

    here is route.config

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace ProductsApp
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
               
    
    
            }
        }
    }
    

    and here is another piece of code

       public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }

    Tuesday, December 15, 2020 12:29 PM

All replies

  • User475983607 posted

    Similarly if i called for get by name http://localhost:6869/api/products?name=Hammer it always return first record

    that means its all good till i checked all methods in Visual studio but in post man its not working fine

    Web API is working exactly as expected.  The problem is you did not follow the instructions from your other post with the same subject; https://forums.asp.net/p/2172909/6327235.aspx?Re+find+by+name+in+web+api.  The URL is...

    https://localhost:44310/api/product/hammer

    The URL you are using in PostMan is invoking the following action.  It's not clear what "products" is though.

    [Route("api/products")]
    public IEnumerable<Product> GetAllProducts()
    {
        return products;
    }

    If you want to use a querystring then you need to change the routing design.  Your previous post showed you are trying to use a URL route.  Do you want to change to a querystring?

    Tuesday, December 15, 2020 2:46 PM
  • User81789783 posted

    can i add item in below array at run time  ??

      Product[] products = new Product[]
            {
                new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
                new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
                new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
            };

    my item is

      var product = new Object();
            product.Id = 4,
           product.Name="apple",
           product.Category= "fruits",
           product.Price= 1.99

    Wednesday, December 16, 2020 11:11 AM
  • User475983607 posted

    The collection in my example is for testing route attributes.  It is not a production approach.  Use a static member to persist the products collection as shown below.  This approach is only good for testing.  

     public class ProductController : ApiController
        {
            static List<Product> products = new List<Product>();
    
            public ProductController()
            {
                if(products.Count() == 0)
                {
                    products.Add(new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 });
                    products.Add(new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M });
                    products.Add(new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M });
                }
            }
    
            //Get: api/product
            [Route("api/product")]
            [HttpGet]
            public IEnumerable<Product> GetAllProducts()
            {
                return products;
            }
    
            //Get: api/product/1
            [Route("api/product/{id:int}")]
            [HttpGet]
            public IHttpActionResult GetProductById(int id)
            {
                var product = products.FirstOrDefault((p) => p.Id == id);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
    
            //Get: api/product/b
            [Route("api/product/{name}")]
            [HttpGet]
            public IHttpActionResult GetProductByName(string name)
            {
                var product = products.FirstOrDefault(p => p.Name == name);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
    
            //post: api/product
            [Route("api/product")]
            [HttpPost]
            public IHttpActionResult Create()
            {
                products.Add(new Product
                {
                    Id = 4,
                    Name = "apple",
                    Category = "fruits",
                    Price = 1.99m
                });
                return Ok();
            }
    
    
        }

    Wednesday, December 16, 2020 12:51 PM
  • User81789783 posted

    yes u r right its not good for production approach because of static then what would be for production ?

    Wednesday, December 16, 2020 1:07 PM
  • User475983607 posted

    yes u r right its not good for production approach because of static then what would be for production ?

    A database.

    Wednesday, December 16, 2020 1:33 PM