确定ASP.NET应用程序是否在本地运行

Sea*_*ean 76 .net asp.net localhost

我想知道是否有一种建议的方法来确定asp应用程序是否在本地运行.目前我使用Request对象并在服务器变量上执行localhost或127.0.0.1的字符串搜索,但这有一些限制.最大的一个是Request对象在我需要时并不总是可用.

Rex*_*x M 145

请参阅HttpRequest.IsLocal

bool isLocal = HttpContext.Current.Request.IsLocal;
Run Code Online (Sandbox Code Playgroud)

  • 请求为空的位置如何.即:Application_start? (5认同)

Ada*_*dam 12

您可以检查Request.IsLocal属性


小智 6

这适用于Application_Start

if (!HostingEnvironment.IsDevelopmentEnvironment)
{
      GlobalFilters.Filters.Add(new RequireHttpsAttribute());
}
Run Code Online (Sandbox Code Playgroud)

要了解有关如何设置IsDevelopmentEnvironment的更多信息,请查看以下主题.

在ASP.NET中,什么决定了HostingEnvironment.IsDevelopmentEnvironment的价值?


Uly*_*ves 5

在回应 @Meh Men 对本线程中其他答案的评论时,他问道:

如果 Request 为空怎么办?即:应用程序_启动?

如果您确定您的网站的生产和测试或“同源”版本将全部与网站的发布版本一起部署,而您的本地环境将以“调试”模式构建和开发,您可以使用#if DEBUGsintax 来编写仅应在本地运行的代码,而在此块之外,甚至在匹配#else块内,您可以编写一些仅在非本地运行时运行的其他代码(例如:远程)。

以下是我在当前正在从事的特定项目中如何解决此问题的一个小示例:

#if DEBUG
    // Code here will only be run locally.
#else
    // Code here will only be run "remotely".
Run Code Online (Sandbox Code Playgroud)