[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)";
}
}
我创建了一个simple plunk来调用这些方法.在我的AngularJS代码中,我正在做两个非常简单的$http调用. GET工作正常.然而,POST总是返回一个“400(Bad Request)”,紧接着在我的WebStorm控制台中,“XMLHttpRequestion无法加载… HTTP状态代码400无效”.
任何和所有的建议赞赏!
编辑!!
您好,感谢您的快速反应.我只是意识到我忘了添加一些非常相关的细节.
我的POST方法的参数是我称之为Envelope对象,它包含两个属性:listingId(int)和Description(string).当我添加urlencoded的Content-Type头文件,并将“{”listingId“:1234,”Description“:”some description“}’作为POST数据传递时,我的POST方法中的服务器上的env参数为NULL(即,似乎无法解析我提供的JSON).对不起,这从原来的帖子中被省略.
解决方法
How do I POST urlencoded form data with $http in AngularJS?
By default,the $http service will transform the outgoing request by
serializing the data as JSON and then posting it with the content-
type,“application/json”. When we want to post the value as a FORM
post,we need to change the serialization algorithm and post the data
with the content-type,“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("&");
}
}).