How do I call an asynchronous method from within an ASPX file (not codebehind)?

270 views Asked by At

I have a DLL that contains an async method for obtaining a report. It does all the heavy lifting, including HTML formatting.

namespace MyReportEngine
{
    public class Renderer
    {
        static public async Task<string> GetReportHtml()
        {
            //Magic (not important)
        }
    }
}

I want to create a web site without doing a lot of work. All I want to have to do is create a simple ASPX file that uses the DLL. I tried this:

<%@ Assembly Name="MyAssembly" %>
<%@ Import Namespace="MyAssembly.MyReportEngine" %>
<%@ Page Async="true" %>

<html>
<body>
    <% =await Renderer.GetReportHtml() %>
</body>
</html>

This results in a runtime exception during JIT compilation:

Compiler Error Message: BC36937: 'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.

I've checked the documentation and tutorials like this one but they only seem to deal with adding async calls to the codebehind. There is no information on how to make the call from the ASPX markup itself. Is it possible?

3

There are 3 answers

0
JobesK On

Wrap it in a seperate method then call that method.

0
Jeremy Thompson On

Are you missing Page.RegisterAyncTask?

public void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(GetReportHtml));
}

Ref: https://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx

0
Paulo Morgado On

Avoid putting code in the markup.

For your use case, you can use a Literal control:

<%@ Assembly Name="MyAssembly" %>
<%@ Import Namespace="MyAssembly.MyReportEngine" %>
<%@ Page Async="true" %>

<html>
<body>
    <asp:Literal id="ReportHtml" runat="server" />
</body>
</html>