LemmyLogic
LemmyLogic

Reputation: 1083

post object to MVC controller using HttpWebRequest, WebClient etc

I have this api controller action that takes an object "ContentList" as parameter.

    [HttpPost]
    public List<string> SendList(string param, ContentList list)
    {
        List<string> testReturn = new List<string> { "test1", "test2", "test3", "test4" };

        return testReturn ;

    }

What I have tried so far is to call a controller action like this:

        Uri _uri = new Uri("http://localhost:xxxxx/api/FakeTest/SendList?param=test");

        var serializer = new JavaScriptSerializer();
        string requestData = serializer.Serialize(new
        {
            list = ContentList,
        });

        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/json";

            var result = client.UploadData(_uri, Encoding.UTF8.GetBytes(requestData));

            var tempString = Encoding.UTF8.GetString(result);
        }

In this example, tempString = ["test1","test2","test3","test4"] as reurned by the controller action..

In the controller action, I can access the properties of the passed in ContentList, and return their values (changing the actions return value accordingly ofcourse).

However, in the controller action, I need to send off the ContentList object for further processing, and this seems to fail. I get a 500 internal server error, and I can't put a breakpoint in the controller to follow the values passed in. The debugger never hits it...

I expect this has something to do with sending json to the controller action.

Anyway, it seems that the ContentList is rejected by the code it is sent to from the controller action, so I figure I need to do some sort of de-serializing, right?

Bottomline, the question is, what is the correct way to call a controller action from code, pass in a C# object, and make it usable from the controller action?

Upvotes: 1

Views: 2971

Answers (1)

Bardo
Bardo

Reputation: 2523

If you are using MVC 3 your controller should be able to reveive and parse json data in a direct way. If you are using MVC 2 you'll need to register a new factory on your application to take care of json parsing on the controller

protected void Application_Start() 
{
  RegisterRoutes(RouteTable.Routes);
  ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

More info on the subject here: http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

Upvotes: 1

Related Questions