Reputation: 2313
I have following method in repository project , and I'm trying to get that value via web api,
Method
public decimal findBookPrice(int book_id)
{
var bookprice = (
from r in context.Books
where r.Book_Id == book_id
select r.Price
).FirstOrDefault();
return bookprice;
}
Book Class
public class Book
{
[Key]
public int Book_Id { get; set; }
[Required]
public string Book_Title { get; set; }
[DataType("decimal(16 ,3")]
public decimal Price { get; set; }
...
}
}
Web API method
// GET: api/BookPrice/3
[ResponseType(typeof(decimal))]
public IHttpActionResult GetBooksPriceById(int id)
{
decimal bookprice = db.findBookPrice(id);
return Ok(bookprice);
}
but once I direct to url which is http://localhost:13793/api/BookPrice/2
I'm getting following output not the decimal value
Upvotes: 1
Views: 2914
Reputation: 15415
The shown error message is caused by a routing problem. The ASP.NET MVC framework was not able to find the right controller or action for the URL
http://localhost:13793/api/BookPrice/2
The default routing rule in ASP.NET MVC takes BookPrice
and tries to find the BookPriceController
. As you stated in your comment, the action is in a BooksWithAuthersController
. Therefore the URL has to be (if you want to use the default routing rule):
http://localhost:13793/api/BooksWithAuthers/2
Have a look at article if you want to read more about this topic.
EDIT:
Looking at the whole controller code you will find the two action methods called GetBooksWithAuthersById
and GetBooksPriceById
. Because both start with get
and have got the same parameter list (int id
), the ASP.NET MVC framework has got two possible action methods for the URL /api/BooksWithAuthors/2
. To solve this ambiguity you can give the GetBooksPriceById
action a separate route via the [Route]
annotation.
Like in this slightly adjusted BooksWithAuthersController:
public class BooksWithAuthersController : ApiController
{
[ResponseType(typeof(BookWithAuther))]
public IHttpActionResult GetBooksWithAuthersById(int id)
{
...
}
[ResponseType(typeof(decimal))]
[Route("api/bookswithauthers/{id}/price")]
public IHttpActionResult GetBooksPriceById(int id)
{
...
}
}
In order get the price of a book, the URL http://localhost:13793/api/BooksWithAuthers/2/price
will return the decimal value.
Upvotes: 1