我正在构建一个MVC网络应用程序,该应用程序将通过WPF本机客户端独家加入。由于我现在设法让这两个应用程序正常通信,我现在想知道如何在我的客户端中正确地查看和操作MVC模型中的对象。
在服务器端,我有两个类Application和Category,这些类被配置为具有多个基数:
public class Application
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ApplicationID { get; set; }
public ICollection<Category> AppCategories { get; set; }
}
public class Category
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CategoryID { get; set; }
public ICollection<Application> AssignedApps { get; set; }
}
我的客户端应用程序可以通过webapi控制器执行所有基本的CRUD操作,但我想知道如何正确地执行操作。
假设我想显示我的所有类别,他们分配的应用程序是以下方法好的还是有更好的战争要做的事情?
public async void GetCategoryList()
{
Categories.Clear();
List<Model.Category> model = null;
try
{
AuthenticationResult result = null;
result = authContext.AcquireToken(AppServiceResourceId, clientId, redirectUri, PromptBehavior.Never);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await httpClient.GetAsync(AppServiceBaseAddress + "/api/CategoriesWebApi");
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
model = JsonConvert.DeserializeObject<List<Model.Category>>(jsonString);
foreach (var cat in model)
{
var currentCategory = new Category();
currentCategory.CategoryID = cat.CategoryID;
currentCategory.Description = cat.Description;
foreach (var item in cat.AssignedCIs)
{
currentCategory.AssignedCIs.Add(item);
}
Categories.Add(cat);
}
}
}
}
感谢任何建议/最佳做法!
答案 0 :(得分:1)
看一下带有一些评论的重构
//DON'T USE ASYNC/AWAIT WITH VOID NO NO NO NO NO NO
//USE TASK
public async Task GetCategoryList() {
try {
AuthenticationResult result = authContext.AcquireToken(AppServiceResourceId, clientId, redirectUri, PromptBehavior.Never);
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
//make call to web api and get response
var response = await httpClient.GetAsync(AppServiceBaseAddress + "/api/CategoriesWebApi");
//check to make sure there is something to read
if (response.IsSuccessStatusCode && response.Content.Headers.ContentLength.GetValueOrDefault() > 0) {
var jsonString = await response.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<List<Model.Category>>(jsonString);
//check to make sure model was deserialized properly and has items
if(model != null && model.Count > 0) {
//shouldn't clear till you have something to replace it with
Categories.Clear();
foreach (var cat in model) {
var currentCategory = new Category();
currentCategory.CategoryID = cat.CategoryID;
currentCategory.Description = cat.Description;
foreach (var item in cat.AssignedCIs) {
currentCategory.AssignedCIs.Add(item);
}
Categories.Add(currentCategory);
}
}
}
} catch { //Notify User/UI of error }
}