0

I am trying to send data from API to web service. But it is always receiving null

Code in API - WEB CLIENT:

 using (var webClient = new WebClient())
                    {
                        webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                        var url = string.Format("End Point URL /SomeAction");
                        var user= new User()
                        {
                            ...
                        };
                        var data = JsonConvert.SerializeObject(user);

                        webClient.UploadString(url, data);
                    }

Service:

 public ActionResult SomeAction([System.Web.Http.FromBody]string data)
        {
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            FOUsers dataFromXBO =
                   (FOUsers)json_serializer.DeserializeObject(data);
//statements
      }

Please advice, How can i receive data that passed from API

Sam1604
  • 1,459
  • 2
  • 16
  • 26

1 Answers1

2

To answer your question directly, to extract a string from a request body, wrap your "string" in another object as per this SO link. ie.

class UserPostRequest{
    public string UserJson{get; set;}
}

And change the signature in your controller as follows:

public ActionResult SomeAction([System.Web.Http.FromBody]UserPostRequest data)

With that said, in this specific instance it's likely that you can just do:

public ActionResult SomeAction([System.Web.Http.FromBody]FOUsers data)

and let the API take care of deserialization for you.

EDIT:

After further research, to add completeness to the first half of my answer let me acknowledge that there are many ways to skin that particular cat. The answer provided is just the one I've historically used. Here's another SO post that enumerates other solutions, including accepting a dynamic or HttpRequestMessage in your API method signature. These would be particularly helpful if for some reason you didn't want to change your client code. That said, again, I don't see a particular reason to do manual serialization if you're just going to end up consuming the out-of-the-box functionality.

chill94
  • 341
  • 1
  • 5