Http.post 从 Angular 2 到 ASP.NET ApiController

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;
}

Angular 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"}; 没有 headers JSON.stringify() 等都没有成功。我如何 Post 数据到 ASP.NET?

这可能是 ASP.NET 和 MVC 处理数据 POST 的方式的问题。

[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

}

您可以参考 my answer here 和参考链接,了解问题的潜在原因。有相当多的服务器端 Web 框架不恰当地处理数据 POST,并且默认情况下不会将数据添加到您的请求 object。

您不应该 [必须] 尝试更改 angular post 的行为并修改 headers 以假装您的数据 post 是一种形式post.

var creds = {
   str: 'testst'
};

$http.post('http://localhost:18937/apitest', JSON.stringify(creds));

Web API 控制器没有变化,它应该可以工作。