简体   繁体   English

在asmx webmethod中使用httpclient

[英]using httpclient in asmx webmethod

is it possible to use httpclient to call a REST service inside an ASMX WebMethod? 是否可以使用httpclient在ASMX WebMethod中调用REST服务? The httpclient library is async and because asmx does not support async await (TAP), I used .Result to force the call to be sync. httpclient库是异步的,并且因为asmx不支持异步等待(TAP),所以我使用.Result强制将调用同步。 However, this time httpclient cannot make the call successfully and I get remote server actively refused connection error. 但是,这次httpclient无法成功进行呼叫,并且我得到远程服务器主动拒绝的连接错误。 if I run the same piece of code in a win forms application using async await or .Result, it works fine. 如果我使用async await或.Result在win窗体应用程序中运行同一段代码,则效果很好。

is this an issue with ASMX WebMethod? ASMX WebMethod有问题吗?

[WebMethod]
public void Get(){

   //Sample (off the top of my head)
   HttpClient client = new HttpClient();
   //more code
   Task.Run(()=> client.GetDocument()).Result;

}

Thanks 谢谢

You could inject a module in the pipeline to handle the processing instead of the actual .asmx code. 您可以在管道中注入一个模块来处理处理,而不是实际的.asmx代码。 But I would suggest before going to the trouble, just use HttpWebRequest . 但我建议在麻烦之前,只需使用HttpWebRequest

Do not do .Result . 不做.Result Do not do Task.Run() in an Asp.Net context. 不要在Asp.Net上下文中执行Task.Run()

The module: 模块:

public class Proxy : IHttpModule
{
    public void Init(HttpApplication context)
    {
        var wrapper = new EventHandlerTaskAsyncHelper(DoAsyncWork);
        context.AddOnBeginRequestAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler);
    }

    async Task DoAsyncWork(object sender, EventArgs e)
    {
        // await... anything
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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