以下代码在访问对应的url时会抛出异常。对象state
inStartNew()
与ctx
in不同ProcessRequest
。为什么会这样?我怎样才能得到一个有效的HttpContextBase
对象StartNew()
?
using System.Web;
using System.Web.Routing;
namespace AsyncUseHttpContextBaseWillFail
{
public class FooHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var ctx = new HttpContextWrapper(context);
System.Threading.Tasks.Task.Factory.StartNew(state =>
{
//ArgumentException: Value does not fall within the expected range.
var ip = ((HttpContextBase)state).Request.UserHostAddress;
}, ctx);
}
public bool IsReusable
{
get { return false; }
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route(string.Empty, new FooRoute()));
}
}
public class FooRoute : IRouteHandler
{
public virtual IHttpHandler GetHttpHandler(RequestContext context)
{
return new FooHandler();
}
}
}