1

我的 webApi 控制器

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

我的 searchCommand 对象

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

我的 webapi 控制器中有一个断点,并且 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 行上有一个断点。

当我尝试进入 webapi 控制器时,我收到 500 错误,它甚至没有命中 webapi 控制器内的断点。以下是我的问题:

  1. 我究竟做错了什么?
  2. 我可以将复杂对象发送到 Web api 请求吗?

编辑:根据 asp.net 论坛和 leons 的指示,我将 WebApi 控制器更改为使用对象而不是接口,它可以工作:

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

你能告诉我如何从结果中重建我的对象吗?

编辑:基于 leon 的建议 - 对于那些对此感兴趣的人,我的最终调用者代码

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

1 回答 1

1

您正在使用 BinaryFormatter?您不应该将您的请求编码为 JSON,因为这就是您要发送的内容吗?

于 2012-06-27T09:22:43.880 回答