尝试在MVC4中使用Async,Task和Await异步进行ValidationAttribute [英] Attempting ValidationAttribute in MVC4 that is asynchronous using Async, Task and Await

查看:211
本文介绍了尝试在MVC4中使用Async,Task和Await异步进行ValidationAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在MVC4中编写一个Validation属性. 目的是检查是否存在应用程序引用(只是一个表示要防止其重复的键的字符串). 我的数据是通过WebAPI访问的,因为我使用的是4.5,所以我希望在可能的情况下使其异步.

I am attempting to write a Validation attribute in MVC4. The purpose is to check for the existence of an application reference (just a string that represents a key I wish to prevent a duplicate for). My data is accessed via WebAPI and because I am using 4.5 I wish to make this asynchronous if possible.

我可能没有充分或适当地使用async和await,但是我想知道如何从继承的Validation类的IsValid方法中调用我的async方法.

I am perhaps not making the best or appropriate usage of async and await but I would like to know how to call my async method from the overridden IsValid method of the inherited Validation class.

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();
    }
}

非常感谢, 丹.

推荐答案

我建议您同步调用WebAPI方法. ValidationAttribute本机不支持异步实现,因此与同步版本相比,您将要编写的任何同步于异步的代码都只是一个hack,实际上并没有提供任何好处.

I recommend that you call your WebAPI methods synchronously. ValidationAttribute does not support asynchronous implementations natively, so any synchronous-over-asynchronous code you'll write is just going to be a hack and not actually provide any benefit as compared to the synchronous version.

这篇关于尝试在MVC4中使用Async,Task和Await异步进行ValidationAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆