我的WebAPI控制器的Web API調用一個複雜的對象作爲參數
[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;}
}
我就行了 HttpWebResponse響應我的WebAPI控制器一個破發點和斷點=(HttpWebResponse)request.GetResponse();
當我嘗試進入webapi控制器時,出現500錯誤,它甚至沒有擊中webapi控制器內的斷點。這裏是我的問題:
- 我在做什麼錯?
- 我可以發送複雜的對象到web api請求嗎?
編輯: 基礎上asp.net論壇和LEONS方向我改變了我的WebAPI控制器使用對象而不是接口,它的工作原理:
[HttpPost]
public SearchProviderCommandResult ExecuteCommand(SearchProviderCommand command)
{
MySearchProvider searchProvider = new MySearchProvider();
return searchProvider.ExecuteCommand(command);
}
你能告訴我怎樣重建我的結果是什麼?
編輯:根據萊昂的建議 - 爲那些有興趣誰在這裏是我最後的調用者的代碼
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; }
}
您可以將自定義對象作爲參數傳遞給動作。根據您使用的屬性前綴的http方法,您可以使用[FromBody]進行發佈。 – gdp
我曾試過,甚至在我發佈這個問題之前,可悲的是,沒有做到這一點,我應該更新我的問題與屬性? –