[英]Pass Data $http.post From AngularJS and ASP.net MVC gets null
[英]Http.post from Angular 2 to ASP.NET ApiController
ASP.NET
[HttpPost]
[Route("apitest")]
public string apitest([FromBody]string str)
{
Console.Writeline(str); // str is always null
return null;
}
角度2:
var creds = "str='testst'" ;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
http.post('http://localhost:18937/apitest', creds, {
headers: headers
})
.map(res => res.json())
.subscribe(
(res2) => {
console.log('subsribe %o', res2)
}
);
我也尝试过creds = {"str":"test"};
没有标头JSON.stringify()
等,但没有成功。 如何将数据发布到ASP.NET?
这可能与ASP.NET和MVC处理数据POSTS的方式有关。
[HttpPost]
public ActionResult Index(int? id)
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
InputClass input = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
input = JsonConvert.DeserializeObject<InputClass>(json)
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do stuff
}
您可以在这里参考我的回答以及有关此问题的潜在原因的参考链接。 有很多服务器端Web框架会不适当地处理数据POSTS,并且默认情况下不会将数据添加到您的请求对象中。
您不应该[必须]尝试更改角度发布的行为,并修改标题以假装数据发布是表单发布。
var creds = {
str: 'testst'
};
$http.post('http://localhost:18937/apitest', JSON.stringify(creds));
Web API控制器中没有任何更改,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.