【问题标题】:AngularJS with WebAPI pass JSON parameters to $http.get带有 WebAPI 的 AngularJS 将 JSON 参数传递给 $http.get
【发布时间】:2016-01-06 19:44:19
【问题描述】:

问题如下:

我想使用带有主体的 get 来使用 RESTful 服务。出于测试目的,我使用 Fiddler Web Debugger。

现在,Fiddler 中的以下 GET 请求得到了我期望的结果:

GET http://localhost:3787/TerminologyService/Autosuggest/ HTTP/1.1
Host: localhost:3787
Content-Length: 215
Content-Type: application/json

{ 
"Text": "war",
"Count": "100",
"MedicationWeight": "7",
"ActivityWeight": "0",
"DiseaseWeight": "0",
"GeneWeight": "0",
"SymptomWeight": "0",
"AnatomyWeight": "0",
"OrderingType": "CATEGORY_DIVERSITY"
}

所以现在我会使用 $http.get 做同样的事情。 这是我目前所拥有的:

function getTerms(text, count, medWeight, actWeight, disWeight, genWeight, symWeight, anaWeight, orderingType)
    {
        var config = {
            headers: {'Content-Type' : 'application/json'},
            params: {Text : text,
                            Count : count,
                            MedicationWeight : medWeight,
                            ActivityWeight : actWeight,
                            DiseaseWeight : disWeight,
                            GeneWeight : genWeight,
                            SymptomWeight : symWeight,
                            AnatomyWeight : anaWeight,
                            OrderingType : orderingType}
        }

        return $http.get(
            'http://localhost:3787/TerminologyService/Autosuggest', config);
    }

这确实形成了一个 GET url:

http://localhost:3787/TerminologyService/Autosuggest?ActivityWeight=0&AnatomyWeight=0&Count=10&DiseaseWeight=0&GeneWeight=0&MedicationWeight=7&OrderingType=CATEGORY_DIVERSITY&SymptomWeight=0&Text=war

很遗憾,这会导致 Web 服务出现错误 500。

当我在 Fiddler 中检查由 $http.get 调用生成的捕获流量时,我发现 JSON 数据没有作为正文传递(显然,因为它是在 URL 中传递的)。所以我无法得到我第一次在 Fiddler 中测试的内容

非常感谢任何帮助

【问题讨论】:

  • 500 表示错误发生在服务器端..您应该通过服务器调试代码..
  • 是的,发生错误是因为请求未按 Web 服务的预期形成。我在 Fiddler 测试中无法通过 GET 正文。
  • Get 请求只通过 URL 传递所有参数..
  • 在 Fiddler 中查看我的 OP 顶部的 GET 请求表明 URL 没有附加任何内容,但我得到了预期的结果。

标签: angularjs json asp.net-web-api get


【解决方案1】:

更新:

问题通过将 GET 改回 POST 来解决。

我错误地认为我应该使用 GET

【讨论】:

    【解决方案2】:

    您不应期望后端的 GET 请求中有正文,但为了回答您的问题,如 $http docs 中所述,您可以将请求的正文消息传递给配置对象的 data 属性。所以使用data 而不是params 它应该有你想要的行为。

    【讨论】:

    • 非常感谢您的回复。我曾假设我应该使用 GET,但事实并非如此。所以我把它改回后端的 Post ,现在它可以工作了。
    猜你喜欢
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2015-11-14
    • 2016-10-06
    相关资源
    最近更新 更多