asp.net-mvc – 异步使用ASP.NET MVC中的WebClient?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 异步使用ASP.NET MVC中的WebClient?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个ASP.NET MVC应用程序,它当前使用WebClient类从控制器操作中对外部Web服务进行简单调用.

目前我正在使用同步运行的DownloadString方法.我遇到了外部Web服务没有响应的问题,这导致我的整个ASP.NET应用程序都缺乏线程并且没有响应.

解决此问题的最佳方法是什么?有一个DownloadStringAsync方法,但我不确定如何从控制器调用它.我需要使用AsyncController类吗?如果是这样,AsyncController和DownloadStringAsync方法如何交互?

谢谢您的帮助.

解决方法

我认为使用AsyncControllers可以帮助您,因为他们从请求线程卸载处理.

我会使用这样的东西(使用this article中描述的事件模式):

public class MyAsyncController : AsyncController
{
    // The async framework will call this first when it matches the route
    public void MyAction()
    {
        // Set a default value for our result param
        // (will be passed to the MyActionCompleted method below)
        AsyncManager.Parameters["webClientResult"] = "error";
        // Indicate that we're performing an operation we want to offload
        AsyncManager.OutstandingOperations.Increment();

        var client = new WebClient();
        client.DownloadStringCompleted += (s,e) =>
        {
            if (!e.Cancelled && e.Error == null)
            {
                // We were successful,set the result
                AsyncManager.Parameters["webClientResult"] = e.Result;
            }
            // Indicate that we've completed the offloaded operation
            AsyncManager.OutstandingOperations.Decrement();
        };
        // Actually start the download
        client.DownloadStringAsync(new Uri("http://www.apple.com"));
    }

    // This will be called when the outstanding operation(s) have completed
    public ActionResult MyActionCompleted(string webClientResult)
    {
        ViewData["result"] = webClientResult;
        return View();
    }
}

并确保您设置所需的任何路由,例如(在Global.asax.cs中):

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapAsyncRoute(
            "Default","{controller}/{action}/{id}",new { controller = "Home",action = "Index",id = "" }
        );
    }
}

猜你在找的asp.Net相关文章