Alex
Alex

Reputation: 2062

Webapi POST results in {object} in MVC Controller

I'm trying to post a string to a MVC Controller and the result is always {object} and I am not able to parse\decode\deserialize it. How can I get that string?

C#:

[HttpPost]
public void Foo(dynamic str)
{
    //str always equals to '{object}'
    var path = @"C:\cookieParserXmlOutput\";
}

Client code:

then((res:any) => {
            let strObj={
                str:res.data
            };
            return this.$http.post("/App/Foo",strObj,{
                headers: { "Content-Type": "application/json; charset=utf-8" }
              });

        }).then((res:any)=>{
            return res;
        })

Upvotes: 0

Views: 68

Answers (2)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41407

Change the content type to text/plain and convert the object to the string using JSON.stringify

return this.$http.post("/App/Foo",JSON.stringify(strObj),{
      headers: { "Content-Type": "text/plain; charset=utf-8" }
});

Upvotes: 0

Jonatan Dragon
Jonatan Dragon

Reputation: 5017

If you want to send an object in POST body, you should also retrieve object in ASP.NET Endpoint method. Wrap your string str into a class:

public class MyRequest
{
    public string Str { get; set; }
}

[HttpPost]
public void Foo(MyRequest request)
{
    ...
}

Upvotes: 2

Related Questions