我有一个静态类,发送电子邮件与链接到我的网站的某些网页。该链接是通过以下代码动态生成的:
UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
string url = urlHelper.Action("Details", "Product", new { id = ticketId }, "http");问题是,我现在还有一个服务,它定期比较创建日期和当前日期,并自动发送这些邮件。当然,代码会崩溃,并表示HttpContext.Current为null (因为它不是请求)。
我尝试过这样的方法:
private static System.Web.Routing.RequestContext requestContext;
private static System.Web.Routing.RequestContext RequestContext {
get
{
if(requestContext == null)
requestContext = HttpContext.Current.Request.RequestContext;
return requestContext;
}
}但是,当我第二次需要RequestContext进行UrlHelper.Action崩溃时,会说是空引用异常。
在通过我的服务调用邮件方法时,我以某种方式未能保存/记住/传递UrlHelper或HttpContext以进行访问。
发布于 2013-09-03 14:58:49
谢谢你的帮助。在我的情况下,预定义URL是没有选择的。我或多或少地找到了解决问题的办法。我知道这可能不是最漂亮的代码,但是它运行得很好,似乎没有人有更好的代码,所以请不要下注。
在global.asax.cs中,我添加了这个类:
class FirstRequestInitialisation
{
private static string host = null;
private static Object s_lock = new Object();
// Initialise only on the first request
public static void Initialise(HttpContext context)
{
if (string.IsNullOrEmpty(host))
{ //host isn't set so this is first request
lock (s_lock)
{ //no race condition
if (string.IsNullOrEmpty(host))
{
Uri uri = HttpContext.Current.Request.Url;
host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
//open EscalationThread class constructor that starts anonymous thread that keeps running.
//Constructor saves host into a property to remember and use it.
EscalationThread et = new EscalationThread(host);
}
}
}
}
}我补充说:
void Application_BeginRequest(Object source, EventArgs e)
{
FirstRequestInitialisation.Initialise(((HttpApplication)source).Context);
}解释了发生了什么:在每个请求上,都会调用FirstRequestInitialisation类,并以上下文作为参数初始化方法。这从来不是一个问题,因为上下文在Application_BeginRequest中是已知的(不像在Application_Start中那样)。初始化方法注意线程仍然只被调用一次,并且有一个锁,这样它就不会崩溃。我取消了我的服务,因为我不能真正与它沟通,相反,我决定用它做一个线程。在这个初始化方法中,我使用主机作为参数调用类构造函数EscalationThread。在这个构造函数中,我创建并启动了一直在运行的线程。
我仍然没有HttpContext,也不能使用UrlHelper,但是我有主机,可以做如下事情:string urlInMail = this.host + string.Format("/{0}/{1}/{2}", "Product", "Details", product.Id);
https://stackoverflow.com/questions/18151014
复制相似问题