我正在构建一个 MVC 网络应用程序,它将通过 WPF native 客户端独占访问。由于我现在设法让这两个应用程序正常通信,我现在想知道如何在我的客户端中正确查看和操作来自 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 Controller 执行所有基本的 CRUD 操作,但我想知道如何正确地执行操作。
假设我想显示我所有的类别,并且他们分配的应用程序是以下方法好吧还是有更好的 war 来做这件事?
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);
}
}
}
}
感谢任何建议/最佳实践!
最佳答案
通过一些评论查看重构
//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 }
}
关于c# - 通过 MVVM 客户端查看和操作 MVC Web 应用程序的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37660065/