【发布时间】:2013-09-13 11:21:11
【问题描述】:
我正在尝试在 MVC4 中编写验证属性。 目的是检查是否存在应用程序引用(只是一个代表我希望防止重复的键的字符串)。 我的数据是通过 WebAPI 访问的,因为我使用的是 4.5,所以如果可能的话,我希望将其设为异步。
我可能没有充分或适当地使用 async 和 await,但我想知道如何从继承的 Validation 类的重写 IsValid 方法中调用我的 async 方法。
public class UniqueApplicationReferenceAttribute : ValidationAttribute
{
public UniqueApplicationReferenceAttribute() : base(() => "The {0} already exists") { }
public int? ApplicationCount { get; set; }
public override bool IsValid(object value)
{
var myTask = GetApplicationRefCountAsync();
myTask.Wait();
this.ApplicationCount = this.ApplicationCount ?? 0;
if (ApplicationCount > 0)
{
return true;
}
else
{
return false;
}
}
public async Task GetApplicationRefCountAsync()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:11111/");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var apps = client.GetStringAsync("api/dataapplications");
await Task.WhenAll(apps);
var appList = apps.Result;
this.ApplicationCount = appList.Count();// apps.Count();
}
}
非常感谢, 丹。
【问题讨论】:
-
C# 4 不常与 MVC 4 一起使用。你的意思是 C# 5 吗?您的 MVC 应用程序是否在 .NET 4.5 上运行?
-
.net 4.5 上的 MVC 4 - 我的大脑被标记阶段溶解了
标签: c#-4.0 asp.net-mvc-4 asynchronous asp.net-web-api async-await