呼叫异步任务<>来自ASP.NET MVC中的控制器

时间:2015-10-20 09:36:14

标签: asp.net-mvc asynchronous

我有一个库包装器OVH API,我尝试调用一个函数来获取ASP.NET MVC项目中的我的使用者密钥。它适用于Console项目应用程序,但该方法永远不会在我的Controller中响应:库中的方法

public async Task<CredentialsResponse> RequestCredential(IEnumerable<AccessRule> accessRules, string redirectUrl = null)
    {
        Ensure.NotNull("accessRules", accessRules);

        CredentialsRequest cmd = new CredentialsRequest();
        cmd.AccessRules.AddRange(accessRules);
        cmd.Redirection = redirectUrl;

        if (cmd.AccessRules.Count == 0)
            throw new ArgumentException("You must specify at least one accessRule");
        return await RawCall<CredentialsResponse>(HttpMethod.Post, "/auth/credential", cmd;
    }

我打电话给控制器:

public ActionResult Index()
    {
        Information infosClient = new Information();

        OvhApiClient api = new OvhApiClient("", "", OvhInfra.Europe);

        CredentialsResponse response = api.RequestCredential(new[]{
            new AccessRule{ Method = "GET", Path = "/*"},
            new AccessRule{ Method = "PUT", Path = "/*"},
            new AccessRule{ Method = "POST", Path = "/*"},
            //new AccessRule{ Method = "DELETE", Path = "/*"},
        }).Result;

        api.ConsumerKey = response.ConsumerKey;

        infosClient.ConsumerKey = api.ConsumerKey;
        return View(infosClient);
    }

我已经尝试了很多没有成功的事情(例如将调用放在async方法中)。

提前感谢您的帮助

1 个答案:

答案 0 :(得分:11)

使控制器操作异步:

public async Task<ActionResult> Index()
{
    ...
    CredentialsResponse response = await api.RequestCredential(...);
    ...
}