【问题标题】:Http.post from Angular 2 to ASP.NET ApiController从 Angular 2 到 ASP.NET ApiController 的 Http.post
【发布时间】:2017-09-15 16:21:48
【问题描述】:

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?

【问题讨论】:

  • 您是否遇到任何错误,或者它是否到达端点但str 为空?
  • 它正在击中控制器,但 str 为空
  • Angular 2 只允许发布字符串顺便说一句?至少 Typescript 是这么说的。
  • 尝试creds = {"str":"test"},然后在http.post 中尝试JSON.stringify(creds),并将标题中的内容类型更改为:application/json

标签: c# asp.net angular post


【解决方案1】:
var creds = {
   str: 'testst'
};

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

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

【讨论】:

  • 我收到ExceptionMessage: "No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'." ExceptionType: "System.Net.Http.UnsupportedMediaTypeException"
  • 我添加了这个解决方案:myadventuresincoding.wordpress.com/2012/06/19/…
  • 尝试将 content-type header = "application/json" 添加到 ajax 请求中
【解决方案2】:

这可能是 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,并且默认情况下不会将数据添加到您的请求对象中。

您不应该 [必须] 尝试更改 Angular 帖子的行为,并修改标题以假装您的数据帖子是表单帖子。

【讨论】:

  • 我使用Web Api,没有Request.InputStream
  • 正确,但您将无法从 FromBody 获取 JSON 数据
猜你喜欢
  • 2017-05-12
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 2017-11-10
  • 2017-03-10
  • 1970-01-01
  • 2017-02-28
  • 1970-01-01
相关资源
最近更新 更多