2014-09-05 18 views
2

我试图做的,使用WinJS.xhrWinJS.xhr没有的HttpRequest将数据传递到网络API

当我做的一切是通过正确地传递不同的是数据的请求的Web API服务的调用(参数)不包含在请求中。

的网页API

[Route("api/Products/GetProductsByCategory")] 
    [HttpGet] 
    public IHttpActionResult GetProductsByCategory([FromBody]int categoryId) 
    { 
     try 
     { 
      //Some logic to return data 
      return Json(_result.AsEnumerable<Models.ProductModel>()); 
     } 
     catch (Exception ex) 
     { 
      //Log error to log file 
      return Content(HttpStatusCode.InternalServerError, "There was a error loading the products. View the log file for more details"); 
     } 
    } 

JavaScript的我用做实际的请求

var url = "http://localhost/rauto.webapi/api/Products/GetProductsByCategory" 
var parameters = 6 
var options = { 
       url: url, 
       responseType: "json", 
       headers: { "Content-type": "application/json" }, 
       data: JSON.stringify(parameters) 
       } 

return WinJS.xhr(options).then(Success, Fail) 

当我微量元素提琴手请求得到以下原始数据

请求:

GET http://localhost/rauto.webapi/api/Products/GetProductsByCategory HTTP/1.1 
Accept: */* 
Content-Type: application/json 
Accept-Language: en-ZA,en;q=0.7,af;q=0.3 
UA-CPU: AMD64 
Accept-Encoding: gzip, deflate 
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; MSAppHost/2.0;  rv:11.0) like Gecko 
Connection: Keep-Alive 
Host: localhost 

回应:

HTTP/1.1 200 OK 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Length: 2 
Content-Type: application/json; charset=utf-8 
Expires: -1 
Server: Microsoft-IIS/8.5 
X-AspNet-Version: 4.0.30319 
X-Powered-By: ASP.NET 
Date: Fri, 05 Sep 2014 07:18:03 GMT 

[] 

为什么数据不附加在httpRequest的主体中?

+0

月1日;最常见的一个“GET”请求使用的URL数据/参数,而不是正文。第2;你的数据似乎不完整。尝试将“参数”从“= 6”改为“= {categoryId:6}” – 2014-09-05 07:32:25

+0

我试过参数{categoryId:6}它仍然有相同的结果。如果我在它的URL中传递参数,但我需要传递正文中的te参数。 – 2014-09-05 07:40:17

回答

0

我个人会让MVC处理它,并在这种情况下使用路由。我相信这会是这样的:

[Route("api/Products/GetProductsByCategory/{categoryId:int}")] 
[HttpGet] 
public IHttpActionResult GetProductsByCategory(int categoryId) 
{ 

不仅仅是参数添加到URL在JavaScript:

var url = "http://localhost/rauto.webapi/api/Products/GetProductsByCategory" 
var parameters = 6 
var options = { 
       url: url+'/'+parameters, 
       responseType: "json", 
       headers: { "Content-type": "application/json" }, 
       } 

return WinJS.xhr(options).then(Success, Fail)