C# Http.post从Angular 2到ASP.NET ApiController
ASP.NETC# Http.post从Angular 2到ASP.NET ApiController,c#,asp.net,angular,post,C#,Asp.net,Angular,Post,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',
[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处理数据发布的方式存在问题
[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
}
[HttpPost]
公共行动结果索引(int?id)
{
Stream req=Request.InputStream;
请求寻道(0,System.IO.SeekOrigin.Begin);
字符串json=newstreamreader(req).ReadToEnd();
InputClass输入=null;
尝试
{
//假设JSON.net/Newtonsoft库来自http://json.codeplex.com/
input=JsonConvert.DeserializeObject(json)
}
捕获(例外情况除外)
{
//尝试处理格式错误的邮件正文
返回新的HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//做事
}
关于问题的潜在原因,您可以参考和引用的链接。有相当多的服务器端web框架不适当地处理数据发布,默认情况下不会将数据添加到请求对象
您不应该[必须]尝试更改角度文章的行为,修改标题以假装数据文章是表单文章
var creds = {
str: 'testst'
};
$http.post('http://localhost:18937/apitest', JSON.stringify(creds));
Web API控制器中没有任何更改,它应该可以工作。可能重复您是否收到任何错误,或者它是否命中端点但str
为空?它命中控制器但str为空。顺便说一句,2只允许过帐字符串?至少Typescript是这样说的。试试creds={“str”:“test”}
然后JSON.stringify(creds)
并将标题中的内容类型更改为:application/json
。我使用Web Api,没有请求。InputStream
正确,但您将无法从FromBody
获取json数据“没有MediaTypeFormatter可用于从媒体类型为“text/plain”的内容中读取“String”类型的对象。”ExceptionType:“System.Net.Http.UnsupportedMediaTypeException”
我添加了此解决方案:尝试将content type header=“application/json”添加到ajax请求中