我如何从MVC3 Razor Controller调用webservice?

Jas*_*raj 5 asp.net-mvc web-services asp.net-mvc-3

在我的项目中,我需要从控制器调用Web服务.我已经完成了以下工作,但它确实有效.

  1. 将Web服务的Web引用添加到项目中.

  2. 按如下方式呼叫服务:

    Service Wservice=new Service();
    Wservice.loginCompleted+=new Wservice_login_Completed;
    WService.login_Async("username","Password");
    
    Run Code Online (Sandbox Code Playgroud)

    注意:每当我调用此服务时,它都会抛出一个错误,"此时无法启动异步操作.异步操作只能在异步处理程序或模块中启动,或者在页面生命周期中的某些事件中启动.如果发生此异常执行页面,确保页面标记为<%@ Page Async ="true"%>."

为了克服这个问题我使用

 [Httppost]
 public ActionResult login(logmodel model)
 {
   Task.Factory.StartNew(() => 
    { 
    Wservice.loginCompleted+=new Wservice_login_Completed;
    WService.login_Async("username","Password");
    });

    if(finalresult==true)
    {
      *** return View();
    }
  }

  void Wservice_login_completed()
  {
      Here i got the output.
  }
Run Code Online (Sandbox Code Playgroud)

但调用Wservice_login_completed()函数是在返回View***之后,所以我没有得到结果.我如何实现"从Controller调用web服务"..任何想法?

Jas*_*raj 2

最后我成功地从 MVC 控制器调用了 web 服务。

注意:添加 ServiceReference 而不是 WebReference 并避免
“Task.Factory.StartNew(()=>);” 过程。

  [Httppost]
 public ActionResult login(logmodel model)
 {
    Wservice.ServiceSoapClient _host = new Wservice.ServiceSoapClient("ServiceSoap");

    var result_out = _host.login(uname, pwd, "test1", "test2", "test3", "test4");
 }
Run Code Online (Sandbox Code Playgroud)

这里的“ServiceSoap”是我们服务的端点。您可能会在 app.confiq 或 web.config 文件中显示该端点。快乐编码...!