在我的应用程序中,它调用webapi,应用程序在MVC5中。现在我在应用程序项目中有更多方法。所以我想创建一个通用(全局)方法来调用api。用于获取内容的方法工作正常,但方法,那些用于发布(意味着保存数据到DB类型)数据,得到这样的错误。代码如下:
public static string SendDataToAPI(dynamic objCommon, string urlParameters, ref string errorMessage)
{
try {
string url = ConfigurationSettingHelper._BaseUrl;
string strJson = string.Empty;
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync(urlParameters, objCommon);
if (response.Result.IsSuccessStatusCode)
{
strJson = response.Result.Content.ReadAsStringAsync().Result;
}
else {
errorMessage = response.Result.Content.ReadAsStringAsync().Result;
}
return strJson;
}
}
catch (Exception ex) {
errorMessage = ex.Message;
return errorMessage;
}
}
所以,我的问题是如何在PostAsJsonAsync
方法中传递动态对象类型?如何设置这种常用方法?
答案 0 :(得分:1)
尝试下面的内容,其中post数据模型通常接受任何类型,复杂对象也应该包装到单个模型中。
public async virtual Task<string> ExecuteHttpApiCall<TModel>(TModel model, string url)
{
HttpResponseMessage response;
using (var client = new HttpClient())
{
if (model != null)
{
response = await client.PostAsJsonAsync(url, model);
}
else
{
response = await client.GetAsync(url);
}
return await response.Content.ReadAsStringAsync();
}
}