may*_*lle 7 c# asp.net asp.net-mvc asp.net-web-api dotnet-httpclient
我试图从客户端发布到Web API方法,如下所示:
// Create list of messages that will be sent
IEnumerable<IMessageApiEntity> messages = new List<IMessageApiEntity>();
// Add messages to the list here.
// They are all different types that implement the IMessageApiEntity interface.
// Create http client
HttpClient client = new HttpClient {BaseAddress = new Uri(ConfigurationManager.AppSettings["WebApiUrl"])};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Post to web api
HttpResponseMessage response = client.PostAsJsonAsync("Communications/Messages", messages).Result;
// Read results
IEnumerable<ApiResponse<IMessageApiEntity>> results = response.Content.ReadAsAsync<IEnumerable<ApiResponse<IMessageApiEntity>>>().Result;
Run Code Online (Sandbox Code Playgroud)
我的Web API控制器操作如下所示:
public HttpResponseMessage Post([FromBody]IEnumerable<IMessageApiEntity> messages)
{
// Do stuff
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,messages当进入Web API控制器操作时,它总是空的(但不是null).我已经在调试器中验证messages了客户端上的对象在发布之前确实有其中的项目.
我怀疑它可能与在尝试传递对象时没有转换为具体类型的接口类型有关,但我不知道如何使其工作.我怎样才能做到这一点?
我想出了如何在没有自定义模型绑定器的情况下完成它.发布答案以防其他人有此问题...
客户:
// Create list of messages that will be sent
IEnumerable<IMessageApiEntity> messages = new List<IMessageApiEntity>();
// Add messages to the list here.
// They are all different types that implement the IMessageApiEntity interface.
// Create http client
HttpClient client = new HttpClient {BaseAddress = new Uri(ConfigurationManager.AppSettings["WebApiUrl"])};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Post to web api (this is the part that changed)
JsonMediaTypeFormatter json = new JsonMediaTypeFormatter
{
SerializerSettings =
{
TypeNameHandling = TypeNameHandling.All
}
};
HttpResponseMessage response = client.PostAsync("Communications/Messages", messages, json).Result;
// Read results
IEnumerable<ApiResponse<IMessageApiEntity>> results = response.Content.ReadAsAsync<IEnumerable<ApiResponse<IMessageApiEntity>>>().Result;
Run Code Online (Sandbox Code Playgroud)
添加到RegisterWebApiConfig.cs中的方法:
config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
Run Code Online (Sandbox Code Playgroud)
关键是将类型作为json的一部分发送并打开自动类型名称处理,以便Web API可以确定它是什么类型.