繁体   English   中英

确定是在没有System.Web的ASP.NET或WinForms / console中运行

[英]Determine whether running in ASP.NET or WinForms/console without System.Web

从类库中,我需要在运行时确定我是在ASP.NET应用程序还是WinForms / console应用程序中运行。 已经有一些 其他 的问题 的问题,但所有这些解决方案都需要增加的System.Web参考。 如果可能的话,在运行我的控制台和WinForms应用程序时,我不想将System.Web程序集加载到内存中,仅用于一行代码中的数千行。

使用System.Diagnostics.Process.GetCurrentProcess().ProcessName

如果您正在运行ASP.NET,那么程序集将被命名为:

  • 如果您运行的是IIS 6.0或IIS 7.0,则名称为w3wp.exe。

  • 如果您运行的是早期版本的IIS,则名称为aspnet_wp.exe。

另一个想法:如何使用AppDomain.CurrentDomain.GetAssemblies()API测试进程/应用程序域是否存在System.Web.dll?

您链接的一个问题包含一个表明Environment.UserInteractive答案

您还可以尝试分析代码的StackTrace ,以确定调用的位置。

你可以尝试一些基于Assembly.GetEntryAssembly()的东西。 如下面的注释所述,如果当前代码在Web应用程序或服务的上下文中运行,则GetEntryAssembly()将返回NULL。 在独立应用程序(如WinForm或控制台应用程序)的情况下,它将返回一些非空引用。

由于评论,编辑改变了原来的答案。

另一个黑客:

如果您没有在独立的exe内运行,System.Configuration.ConfigurationManager.OpenExeConfiguration会抛出带有特定消息的ArgumentException。 您可以使用这个事实来检查这种方式:

bool notAnExe = false ;
try
{
    // see if we're running in an exe.
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
catch(ArgumentException aex)
{
    if(aex.Message == "exePath must be specified when not running inside a stand alone exe.")
    {
        notAnExe = true ;
    }
}

您可以检查System.Diagnostics.Process.GetCurrentProcess()。ProcessName;。 如果它以aspnet开头,那就是asp.net。 否则,桌面。

它可能看起来像一个黑客。 它使用DomainManager类型的Current AppDomain。 还检查AppDomainManager

public static class AspContext
{
    public static bool IsAspNet()
    {
        var appDomainManager = AppDomain.CurrentDomain.DomainManager;
        return appDomainManager != null && appDomainManager.GetType().Name.Contains("AspNetAppDomainManager");
    }
}

或者你可以在SO上使用这个其他答案

这是一个老线程,但这里是一个新的答案,不是黑客。

private bool IsExe()
{
  var domainManager = AppDomain.CurrentDomain.DomainManager;
  if (domainManager == null) return false;

  var entryAssembly = domainManager.EntryAssembly;
  if (entryAssembly == null) return false;

  return entryAssembly.Location.EndsWith(".exe", StringComparison.OrdinalIgnoreCase);
}

这不会告诉你应用程序是否是ASP.Net,但它会告诉你这是一个控制台或WinForms应用程序,这是与大多数其他答案相反的方法。 例如,如果这是一个OWIN应用程序,即使这不是ASP.Net应用程序, IsExe方法也将返回false。

HostingEnvironment.IsHosted

MSDN文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM