ASP.NET MVC - HttpRequestWrapper.Url 为空?
我的应用程序发送一些电子邮件,并且电子邮件中引用的图像路径需要根据用户访问发送电子邮件的页面的方式而变化。我之前多次使用过代码的变体,没有出现任何问题,但这是我第一次尝试在 MVC 应用程序中执行此操作:
var relImagePath = controllerContext.HttpContext.Response.ApplyAppPathModifier("~/Emails/Images");
var absImagePath = new Uri(controllerContext.HttpContext.Request.Url, relImagePath).AbsoluteUri;
第二行抛出 NullReferenceException,因为 HttpContext.Request.Url 为 null。怎么可能呢?
编辑:我应该注意,我在与处理请求的线程分开的线程池线程中运行此代码。如果我将此代码移回到执行控制器操作的线程上,则 url 就在那里。目前,我已采取在同一线程上执行代码的方法。
My application sends out some emails, and the image paths referenced in the e-mails need to vary depending on how the user accessed the page that is sending the email. I've used variations of the code before many times with no problem, but this is the first time I'm trying to do it in an MVC app:
var relImagePath = controllerContext.HttpContext.Response.ApplyAppPathModifier("~/Emails/Images");
var absImagePath = new Uri(controllerContext.HttpContext.Request.Url, relImagePath).AbsoluteUri;
The second line is throwing an NullReferenceException because HttpContext.Request.Url is null. How can that be?
Edit: I should note that I'm running this code in a thread pool thread separate from the one that processed the request. If I move this code back onto the thread executing the controller action, the url is there. For now, I've resorted to executing the code on the same thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
HttpContext 可能并不总是可以在线程中访问。您需要将所需的信息传递给线程:
或者如果您正在使用线程池(仅适用于短期运行的任务):
The HttpContext might not always be accessible in threads. You will need to pass the required information to the thread:
or if you are using the ThreadPool (only for short running tasks):
我认为 RequestContext 在您调用controllerContext.HttpContext时获取当前的HttpContext(因为它向RequestContext询问HttpContext),并且我认为它可能只是询问HttpContext.Current,这就是为什么得到null。
尝试在 ASP.NET 线程中获取controllerContext.HttpContext,保存它并传递给您自己的线程,而不是稍后在错误的时间请求 HttpContext 的控制器上下文。
这是我的猜测。
另外,http://csharpfeeds.com/post/5415/Dont_use_the_ThreadPool_in_ASP.NET.aspx< /a>
I would suppose that RequestContext grabs current HttpContext at the time you call controllerContext.HttpContext (since it asks RequestContext for the HttpContext), and I suppose that it may just ask HttpContext.Current, and that's why get null.
Try to grab controllerContext.HttpContext in the ASP.NET thread, save it and pass to your own thread, instead of controller context which asks for HttpContext at wrong time later.
That's my guess.
Also, http://csharpfeeds.com/post/5415/Dont_use_the_ThreadPool_in_ASP.NET.aspx
这个覆盖似乎也有效:
This override also seems to work: