2016-09-16 102 views
1

我有以下的库项目的方法,而我试图让通过网络的API值,返回十进制值

方法

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 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方法

// GET: api/BookPrice/3 

    [ResponseType(typeof(decimal))] 
    public IHttpActionResult GetBooksPriceById(int id) 
    { 
     decimal bookprice = db.findBookPrice(id); 

     return Ok(bookprice); 
    } 

,但一旦我直接到URL是http://localhost:13793/api/BookPrice/2

我得到下面的输出不是十进制值

enter image description here

+0

您最好返回XML或JSON的响应类型,然后反序列化客户端应用程序上的响应。 –

+0

@Ephraim我是新来的这个网页api,你能告诉我怎么做吗? – kez

+2

无论模型中的小数类型如何,路由都必须存在问题。您的WebAPIController是否也命名为“BookPriceController”? –

回答

1

所显示的错误消息由路由问题引起的。 ASP.NET MVC框架没能找到合适的控制器或动作的URL

http://localhost:13793/api/BookPrice/2 

在ASP.NET MVC的默认路由规则需要BookPrice并试图找到BookPriceController。正如您在评论中所述,此操作位于BooksWithAuthersController。因此,URL必须是(如果你想使用默认的路由规则):

http://localhost:13793/api/BooksWithAuthers/2 

看一看article,如果你想了解更多关于这个话题。

编辑:

放眼整个controller code,你会发现这两个动作方法称为GetBooksWithAuthersByIdGetBooksPriceById。因为两者都从get开始并且具有相同的参数列表(int id),所以ASP.NET MVC框架对URL /api/BooksWithAuthors/2有两种可能的操作方法。为了解决这个模糊问题,您可以通过[Route]注释为GetBooksPriceById动作提供单独的路线。

如在此略作调整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) 
    { 
     ... 
    } 
} 

为了得到一本书的价格,网址http://localhost:13793/api/BooksWithAuthers/2/price将返回十进制值。

+0

请看这整个代码,前两个方法工作正常,最后小数返回不工作在这里,你可以看看整个代码在这里https://bitbucket.org/snippets/Common_Admin/Gp5ek – kez

+0

@kez:我已经扩展我的答案反映模棱两可的行动方法 –

+0

thnks为您的答案,这'价格'如何识别为十进制类型的URL,或者它使用作为唯一标识符? – kez