Quantcast
Channel: Web API
Viewing all articles
Browse latest Browse all 4850

API URL issue

$
0
0

Hi,

I am trying to create REST API using asp.net 4.5.  As i am using version 4.5 i thought of writing Router prefix on controller level instead of  mentioning in  WebAPIconfig level.

Below is my sample code

[RoutePrefix("api/products")]
    [RoutePrefix("products")]
    public class ProductsController : ApiController
    {
        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 } 
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        
        [Route("{id:int}")]
        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        
        [Route("{Name}")]
        public IHttpActionResult GetProductByName(string Name)
        {
            var product = products.FirstOrDefault((p) => p.Name == Name);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

       
         [Route("{Name},{ID}")]
        public IHttpActionResult GetProductByName(string Name, int ID)
        {
            var product = products.FirstOrDefault((p) => (p.Name == Name && p.Id == ID));
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }

I am not sure is my code controller class correct.

 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, action = RouteParameter.Optional }
            );
}

Below is the sample url which is working,

http://localhost:8020/api/products

http://localhost:8020/api/products/1

Below url is not working 

http://localhost:8020/api/products/name=hammer

http://localhost:8020/api/Products/name=hammer&Id=1

Any suggestion what am i doing wrong. Please help me to achieve this.


Viewing all articles
Browse latest Browse all 4850


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>