Vijay V
Vijay V

Reputation: 389

Web Api call with a complex object as parameter

My webApi Controller

[HttpPost]
public ISearchProviderCommandResult ExecuteCommand(ISearchProviderCommand command)
{
  MySearchProvider searchProvider = new MySearchProvider();
  return searchProvider.ExecuteCommand(command);
}

My searchCommand object

[Serializable]
class SearchProviderCommand : ISearchProviderCommand
{
  public string OperationContext {get; set;}
  public string OperationId{get; set;}
}

I have a break point in my webapi controller and a breakpoint on the line HttpWebResponse response = (HttpWebResponse)request.GetResponse();

When I try to step into the webapi controller, I get a 500 error and it doesnt even hit the breakpoint inside the webapi controller. Here are my questions:

  1. What am I doing wrong?
  2. Can I send complex objects to web api requests?

EDIT: Based on the asp.net forums and leons directions I changed my WebApi controller to use an object instead of the interface and it works:

[HttpPost]
public SearchProviderCommandResult ExecuteCommand(SearchProviderCommand command)
{
  MySearchProvider searchProvider = new MySearchProvider();
  return searchProvider.ExecuteCommand(command);
}

Can you tell me how I reconstruct my object from the result?

EDIT: Based leon's suggestion - for those who are interested here is my final caller code

public result ExecuteCommand(ISearchProviderCommand searchCommand)
{
  //serialize the object before sending it in
  JavaScriptSerializer serializer = new JavaScriptSerializer();
  string jsonInput = serializer.Serialize(searchCommand);

  HttpClient httpClient = new HttpClient() { BaseAddress = new Uri(ServiceUrl) };
  StringContent content = new StringContent(jsonInput, Encoding.UTF8, "application/json");
  var output = httpClient.PostAsync(ServiceUrl, content).Result;

  //deserialize the output of the webapi call
  result c = serializer.Deserialize<result>(output.Content.ReadAsStringAsync().Result);

  return c;
 }
}

public class result : ISearchProviderCommandResult
{
  public object Result { get; set; }
}

Upvotes: 1

Views: 4466

Answers (1)

leon.io
leon.io

Reputation: 2824

You're using a BinaryFormatter? Shouldn't you be encoding your request as JSON since that's what you're sending?

Upvotes: 1

Related Questions