[英]How to determine if .NET code is running in an ASP.NET process?
我有一个通用类的实例,它将在ASP.NET和独立程序下执行。 此代码对正在运行的进程很敏感 - 也就是说,如果在ASP.NET下运行,则不应调用certin方法。 如何确定代码是否在ASP.NET进程中执行?
我目前使用的解决方案将在下面解答。
我希望有人会就为什么这个问题得到落实和/或提出更好的方式来提出评论! 我只能假设至少有些人已经看过这个问题并说“什么是白痴,ASP.NET代码是.NET代码”。
如果您使用异步方法,则HttpContext.Current在ASP.NET中也可以为null,因为异步任务发生在不共享原始线程的HttpContext的新线程中。 这可能是您想要的,也可能不是,但如果没有,那么我相信HttpRuntime.AppDomainAppId在ASP.NET进程的任何地方都是非null而在其他地方是null。
尝试这个:
using System.Web.Hosting;
// ...
if (HostingEnvironment.IsHosted)
{
// You are in ASP.NET
}
else
{
// You are in a standalone application
}
为我工作!
有关详细信息,请参阅HostingEnvironment.IsHosted
我认为你真正想做的是重新思考你的设计。 更好的方法是使用Factory类生成所需类的不同版本(旨在实现接口以便可以互换使用它们),具体取决于应用程序的启动方式。 这将本地化代码,以在一个地方检测基于Web和非基于Web的使用,而不是将其全部分散到您的代码中。
public interface IDoFunctions
{
void DoSomething();
}
public static class FunctionFactory
{
public static IDoFunctions GetFunctionInterface()
{
if (HttpContext.Current != null)
{
return new WebFunctionInterface();
}
else
{
return new NonWebFunctionInterface();
}
}
}
public IDoFunctions WebFunctionInterface
{
public void DoSomething()
{
... do something the web way ...
}
}
public IDoFunctions NonWebFunctionInterface
{
public void DoSomething()
{
... do something the non-web way ...
}
}
using System.Diagnostics;
if (Process.GetCurrentProcess().ProcessName == "w3wp")
//ASP.NET
这是我对这个问题的回答。
首先,确保您的项目引用System.Web并且您的代码文件是“使用System.Web;”。
public class SomeClass {
public bool RunningUnderAspNet { get; private set; }
public SomeClass()
//
// constructor
//
{
try {
RunningUnderAspNet = null != HttpContext.Current;
}
catch {
RunningUnderAspNet = false;
}
}
}
If HttpContext Is Nothing OrElse HttpContext.Current Is Nothing Then
'Not hosted by web server'
End If
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.