我需要一些关于如何修复代码的建议。我正在研究一些具有大量依赖关系的现有项目,因此我需要修改的越多越好。在这种情况下,我的控制器需要BuildingReportModel作为LIST,并且最后该控制器将此列表返回到某个视图。我的问题是当我尝试调用接收模型/类的GetWSObject时,没有LIST。如何使这段代码工作的最佳方式或最佳实践? BuildingReportModel需要声明为List<>因为我之前有一些无法改变的验证。有什么建议吗?
List<BuildingReportModel> rc = new List<BuildingReportModel>();
BuildingWSObjects ws = new BuildingWSObjects();
rc = await ws.GetWSObject<BuildingReportModel>("all");
return View(rc);
public class BuildingReportModel
{
public string message1 { get; set; }
public string message2 { get; set; }
}
public class BuildingWSObjects
{
public async Task<T> GetWSObject<T>(string uriActionString)
{
T returnValue =
default(T);
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/logger");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(uriActionString);
response.EnsureSuccessStatusCode();
returnValue = JsonConvert.DeserializeObject<T>(((HttpResponseMessage)response).Content.ReadAsStringAsync().Result);
}
return returnValue;
}
catch (Exception e)
{
throw (e);
}
}
}
答案 0 :(得分:2)
我会修改BuildingWSObjects
类并添加新方法:
public async Task<List<T>> GetWSObjects<T>(string uriActionString)
{
return new List<T> { await this.GetWSObject<T>(uriActionString)};
}
答案 1 :(得分:1)
将列表传递给GetWSObject,而不是返回列表。
rc = await ws.GetWSObject<List<BuildingReportModel>>("all");