如何从 MVC4 控件(.ascx 文件)调用异步方法?

How can I call an async method from an MVC4 control (an .ascx file)?

我的 MVC4 应用程序被重构以引入一些异步代码。但是,有几个 .ascx 和 .aspx 文件是调用异步方法。例如,

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeModel>" %>
<div id="connection-config-settings">
    <%
        var authorizationContext = this.AuthorizationContext();
        if (await authorizationContext.ConfigurationAuthorization.CanUserUpdateConfig())
        {
     %>
             <pre>The user can update configuration</pre>
      <% }
         else
         {
       %>
             <pre>The user can NOT update configuration</pre>
       <%
         }
       %>
</div>

毫不奇怪,我收到一条错误消息,指出 await 只能在标有 'async' 的方法中使用。我真的不想通过使用 GetAwaiter().GetResult() 或 .Result 或其他技巧来阻止异步调用。我已经阅读了很多关于异步编程的最佳实践,以下两个资源强烈建议永远不要阻止异步调用。

How to call asynchronous method from synchronous method in C#?

https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

如何从我的 .ascx 文件中调用异步方法?

异步在 ASP.NET Web Forms 4.5 中是 possible

首先,将您的代码移动到 *.aspx(ascx).cs 后端。

其次,像这样注册你的异步方法:

public bool UserCanUpdate = false;

protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(UserCanUpdateAsync));
}

private async Task UserCanUpdateAsync()
{
    var authorizationContext = this.AuthorizationContext();
    UserCanUpdate = await authorizationContext.ConfigurationAuthorization.CanUserUpdateConfig();
}

第三,将 Control 属性添加到您的 Page (Control) 指令

<%@ Control Async="true" Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeModel>" %>

我采用的解决方案是不在 .aspx 或 .ascx 文件中进行任何异步调用。相反,将异步方法调用中的数据加载到异步控制器中的 ViewData 中,您就可以一起绕过这个问题。