asp.net-mvc – 异步使用ASP.NET MVC中的WebClient?
发布时间:2020-05-28 14:14:55 所属栏目:asp.Net 来源:互联网
导读:我有一个ASP.NET MVC应用程序,它当前使用WebClient类从控制器操作中对外部Web服务进行简单调用. 目前我正在使用同步运行的DownloadString方法.我遇到了外部Web服务没有响应的问题,这导致我的整个ASP.NET应用程序都缺乏线程并且没有响应. 解决此问题的最佳方法
|
我有一个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-mvc – MiniProfiler与EF“模型第一”edmx模型
- asp.net – 为什么aspx代码隐藏文件被声明为部分类?
- asp.net-mvc – HTML5元素的“传说”太少了
- asp.net-mvc – 使用没有ORM的ASP.NET MVC
- asp.net-mvc – 如何在ASP.NET MVC中使用单选模式创建ListB
- asp.net – 更好的方式来获取页面名称
- ASP.NET MVC4代码优先 – ‘无法附加文件作为数据库’异常
- ASP.NET Core 2.0中Razor页面禁用防伪令牌验证
- asp.net – 为什么在“Glimpse Web Debugger”中没有显示“
- asp.net-mvc – 在ASP.NET MVC6中访问querystring
推荐文章
站长推荐
- asp.net – 什么是连接池?
- asp.net-mvc-3 – 我需要什么样的路线才能提供虚
- asp.net-mvc-3 – MVC 3 WebGrid – 可以进行内联
- asp.net-mvc – asp.net mvc 4将表单从站点发送到
- ASP.NET MVC2与实体框架4 – AsEnumerable()或To
- asp.net-mvc – Asp.Net Mvc – 在ActionResult.
- asp.net-mvc – ASP.NET MVC 3 Treeview
- asp.net – 来自TextBox的ActionLink routeValue
- asp.net-mvc – enable-migrations错误:项目无法
- asp.net-mvc – 洋葱建筑 – 存储库与服务?
热点阅读
