C# 此时无法启动异步操作 调用 WebService 时发生异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17101708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:35:26  来源:igfitidea点击:

An asynchronous operation cannot be started at this time Exception occurs on calling WebService?

c#asp.net-mvc-3web-servicesasynchronousexception-handling

提问by Jasper Manickaraj

In my ASP.NET MVC 3 project I'm calling a web service for login authentication. But it throws an exception:

在我的 ASP.NET MVC 3 项目中,我正在调用 Web 服务进行登录身份验证。但它抛出一个异常:

Asynchronous Exception

异步异常

Exception Details:

异常详情:

An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>.

此时无法启动异步操作。异步操作只能在异步处理程序或模块内或在页面生命周期中的某些事件期间启动。如果在执行 Page 时发生此异常,请确保将 Page 标记为 <%@ Page Async="true" %>。

How to fix this issue?

如何解决这个问题?

采纳答案by Patrick Magee

Make sure that your Controller method returns an async Task.

确保您的 Controller 方法返回一个异步任务。

public class ServiceController : Controller 
{
    public async Task<ActionResult> Index()
    {       
        var service = new Service();
        await service.CallMethodAsync();    
        return View();
    }
}

Basically, the documentation is written in a way where they believe you are only using ASP.NET WebForms, however obviously you can use this in MVC applications too, so their documentation needs to be updated.

基本上,文档的编写方式他们认为您只使用 ASP.NET WebForms,但显然您也可以在 MVC 应用程序中使用它,因此他们的文档需要更新。

回答by Yahya-Imam Munir

You are calling an ASYNC method therefore you must add Async="true" inside your page declaration <%@ Page .....%>.

您正在调用 ASYNC 方法,因此您必须在页面声明 <%@ Page .....%> 中添加 Async="true"。