【问题标题】:WinJS.xhr not passing data in httpRequest to Web ApiWinJS.xhr 未将 httpRequest 中的数据传递给 Web Api
【发布时间】:2014-09-05 17:39:36
【问题描述】:

我正在尝试使用 WinJS.xhr 调用 Web 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的正文中没有附加数据?

【问题讨论】:

  • 第一;最常见的“GET”请求使用数据/参数的 URL,而不是正文。第二;你的数据似乎不完整。尝试将“参数”从“= 6”更改为“= { categoryId:6 }”
  • 我试过参数为 { categoryId: 6 } 它仍然有相同的结果。如果我在 URL 中传递参数,它可以工作,但我需要在正文中传递 te 参数。

标签: javascript asp.net-web-api winjs


【解决方案1】:

我个人会让 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2012-04-16
    相关资源
    最近更新 更多