非常简单的AngularJS $ http POST结果为'400(错误请求)'和'无效的HTTP状态代码400'

Ear*_*rlD 10 javascript azure angularjs

我在Azure中托管了一个非常简单的.NET Web API,它有两个非常简单的方法:

[EnableCors(origins: "http://simpleapiearl.azurewebsites.net", headers: "*", methods: "*")]
public class EnvelopesController : ApiController {
    // GET: api/Envelopes
    public IEnumerable<string> Get() {
        return new string[] { "value1", "value2" };
    }

    // POST: api/Envelopes
    public string Post([FromBody]Envelope env) {
        return "rval: " + env + " (and my addition to env)";
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个简单的插件来调用这些方法.在我的AngularJS代码中,我正在进行两个非常简单的$ http调用.GET工作正常.然而,POST总是返回"400(错误请求)",紧接着在我的WebStorm控制台中"XMLHttpRequestion无法加载......无效的HTTP状态代码400".

任何和所有建议赞赏!

编辑!!

您好,感谢非常快速的回复.我刚刚意识到我忘了添加一些非常相关的细节.

我的POST方法的参数是我称之为Envelope的对象,它包含两个属性:listingId (int)Description (string).当我添加urlencoded的Content-Type标头,并'{"listingId":1234, "Description":"some description"}'作为我的POST数据传递时,我在服务器上的POST方法中的env参数是NULL(也就是说,它似乎无法解析我提供的JSON).对不起,这是原始帖子中省略的.

all*_*kim 17

我认为这篇文章会有所帮助.

如何在AngularJS中使用$ http发布urlencoded表单数据?

默认情况下,$ http服务将通过将数据序列化为JSON来转换传出请求,然后使用内容类型"application/json"发布它.当我们想要将值作为FORM帖子发布时,我们需要更改序列化算法并使用内容类型"application/x-www-form-urlencoded"发布数据.

这是你的修改过的plnkr.您的代码缺少JSON到已编码网址的转换.

http://plnkr.co/edit/4aeEDz73qgHSfOv1sBgn?p=preview

$http({
    method: 'POST',
    url: 'http://simpleApiEarl.azurewebsites.net/api/envelopes',
    data: env,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
      var str = [];
      for(var p in obj)
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      return str.join("&");
    }
  }).
Run Code Online (Sandbox Code Playgroud)