Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
with this URI
http://localhost:2259/api/ServiceA/1234"

where isbn=1234 isbn value is 1234 in database

I am getting Null . While i have data in the database which should be shown here

What I have tried:

my webapiconfig
public static class WebApiConfig
   {
       public static void Register(HttpConfiguration config)
       {
           config.MapHttpAttributeRoutes();

           config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{isbn}",
               defaults: new { isbn = RouteParameter.Optional }
           );
       }



and my service A Controller
public class ServiceAController : ApiController
   {


       [HttpGet]
       public Book GetBook(string isbn)
         {

           using (AppDbContext db = new AppDbContext())

           {

               var query = from b in db.Books

                           where b.ISBN == isbn && b.Source == "Book Store 1"

                           select b;

               return query.SingleOrDefault();

           }

       }
   }
Posted
Updated 4-Mar-17 11:01am

1 solution

Well, you're getting null because your query WHERE condition doesn't match any records.

Put a breakpoint on the using line and check the value of isbn. Chances are good its value is not what you think it is.
 
Share this answer
 
Comments
codegeekalpha 4-Mar-17 17:22pm    
if i use [route("api/serviceA/1234")] i get the results with uri localhost/1234
but i want resutls to be retrived on localhost/api/serviceA/1234
Dave Kreskowiak 4-Mar-17 19:07pm    
Use [RoutePrefix("/api/controllerName")] on the controller class instead.

Then you can use [Route("{isbn}")] on the GetBook method.

You shoud then be able to use http://localhost/api/ServiceAController/GetBook/1234 to get the content.
codegeekalpha 4-Mar-17 19:43pm    
i did as you said ..
http://localhost:2280/1234
I am getting {"Id":1,"ISBN":"1234","Title":"Title 1","Publisher":null,"Author":"Farooq","Price":35000.00,"Source":"Book Store 2","PurchaseUrl":null}


and with this
http://localhost:2280/api/ServiceA/1234

i am getting null
Bryian Tan 4-Mar-17 19:58pm    
Your code look fine here. I tested it. Unless you omitted some details. Look like this question is a re-post from Web API 2 is not retrieving data from database[^]

Is the webapi on a separate project or in the web project?
Dave Kreskowiak 4-Mar-17 20:04pm    
You can't do that. You're giving the controller name but no method name. It has no idea you want to call the GetBook method unless you specify it. To remove that is just stupid because you would then only get to put a single method in the controller.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900