简体   繁体   中英

How to make simple async action method returning content return actual content and not type

here is a very simply MVC asynchronous action:

    [HttpPost]
    public async Task<ContentResult> Trial()
    {
        ContentResult contentResult = await new Task<ContentResult>(()=>new ContentResult{Content="Hi"});
        return contentResult;
    }

I would expect a post to this action to respond with the content "Hi". But it does not. It responds with the content "System.Threading.Tasks.Task`1[System.Web.Mvc.ContentResult]".

Here is the full response:

    HTTP/1.1 200 OK
    Cache-Control: no-cache, no-store
    Pragma: no-cache
    Content-Type: text/html; charset=utf-8
    Content-Encoding: gzip
    Expires: -1
    Vary: Accept-Encoding
    X-UA-Compatible: IE=Edge
    Date: Mon, 23 Nov 2020 17:02:37 GMT
    Content-Length: 166
    
    System.Threading.Tasks.Task`1[System.Web.Mvc.ContentResult]

Would love some insights into why, and how to get the content "Hi" as expected, using an Async function. Thanks.

This can happen if you're using a very old version of MVC. You must be running (at least) ASP.NET 4.5 on .NET Framework 4.5 for Task-returning action method to work. Microsoft.Bcl.Async does not work for ASP.NET projects.

If you have .NET Framework 4.5 or newer on your web servers, you can upgrade your project to ASP.NET 4.5. After upgrading, you must turn off "quirks mode" for async to work properly . I prefer to do this by setting httpRuntime.targetFramework in your web.config to 4.5 (or whatever version you upgrade to).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM