2

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

I also tried creds = {"str":"test"}; without headers JSON.stringify() etc. without success. How do I Post data to ASP.NET?

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
daniel
  • 34,281
  • 39
  • 104
  • 158

2 Answers2

0

This is probably an issue with the way that ASP.NET and MVC handle data 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

}

You can refer to my answer here and the referenced links as to a potential cause of the issue. There are quite a few server side web frameworks that inappropriately handle data POSTS and by default doesn't add the data to your request object.

You shouldn't [have to] try and change the behavior of your angular post, and modify headers to pretend your data post is a form post.

Community
  • 1
  • 1
Sean Larkin
  • 6,290
  • 1
  • 28
  • 43
0
var creds = {
   str: 'testst'
};

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

No changes in Web API controller and it should work.

Maciej Wojsław
  • 403
  • 2
  • 10
  • I get `ExceptionMessage: "No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'." ExceptionType: "System.Net.Http.UnsupportedMediaTypeException"` – daniel Nov 17 '15 at 09:40
  • I added this solution: https://myadventuresincoding.wordpress.com/2012/06/19/c-supporting-textplain-in-an-mvc-4-rc-web-api-application/ – daniel Nov 17 '15 at 09:59
  • Try add content-type header = "application/json" to ajax request – Maciej Wojsław Nov 17 '15 at 10:31