我正在尝试使用WinJS.xhr调用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)
当我在Fiddler中跟踪请求时,我得到以下原始数据
请求:
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 :(得分:0)
我个人会让MVC处理它并在这种情况下使用路由。我相信它会是这样的:
[Route("api/Products/GetProductsByCategory/{categoryId:int}")]
[HttpGet]
public IHttpActionResult GetProductsByCategory(int categoryId)
{
只需将参数添加到JavaScript中的URL:
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)