WEB API中通过方法重载传递多个参数 [英] multiple parameters passing with method overloading in WEB API
问题描述
我在存储库类中有以下方法
I have following methods in Repository Class
public class LibraryRepository : IBookRepository
{
LibraryContext context = new LibraryContext();
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;
}
public decimal findBookPrice(int book_id, string bookname)
{
var bookprice = (
from book in context.Books
where book.Book_Id == book_id & book.Book_Title == bookname
select book.Price
).FirstOrDefault();
return bookprice;
}
}
然后,我尝试在Web API中分别获取这两种方法
Then I'm trying to get those two methods separately in Web API
public class BooksWithAuthersController : ApiController
{
private LibraryRepository db = new LibraryRepository();
// GET: api/BooksWithAuthers/id/Price
[ResponseType(typeof(decimal))]
[Route("api/BooksWithAuthers/{id}/Price")]
public IHttpActionResult GetBooksPriceById(int id)
{
decimal bookprice = db.findBookPrice(id);
return Ok(bookprice);
}
// GET: api/BooksWithAuthers/id,name/Price
[ResponseType(typeof(decimal))]
[Route("api/BooksWithAuthers/{id,name}/Price")]
public IHttpActionResult GetBooksPriceById(int id,string name)
{
decimal bookprice = db.findBookPrice(id,name);
return Ok(bookprice);
}
}
第一种方法可以正常工作,但是如何处理具有多个参数的方案
Here first method working fine, but How can I handle scenario with multiple parameters
推荐答案
我不确定这个 {id,name}
甚至是否可能.由于路由模块读取5,因此您正在获取异常.,测试为单个属性,并且无法将其序列化为方法
I am not sure if this {id,name}
is even possible.You are getting the exception because routing module is reading 5,test as single attribute and is not able serialize it to int for method
公共IHttpActionResult GetBooksPriceById(int id)
您需要根据可空类型(int?)更改以下方法,并更改路由
You need to change your methods as below considering nullable types (int?) and also change the route
[ResponseType(typeof(decimal))]
[Route("api/BooksWithAuthers/{id}/Price")]
public IHttpActionResult GetBooksPriceById(int? id)
{
decimal bookprice = db.findBookPrice(id);
return Ok(bookprice);
}
[ResponseType(typeof(decimal))]
[Route("api/BooksWithAuthers/{id}/{name}/Price")]
public IHttpActionResult GetBooksPriceById(int? id,string name = null)
{
decimal bookprice = db.findBookPrice(id,name);
return Ok(bookprice);
}
参考- https://msdn.microsoft.com/zh-cn/library/1t3y8s4s.aspx
这篇关于WEB API中通过方法重载传递多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!