我编写了一个代码库,它既可以用于桌面应用程序,也可以用于web服务器。这个库有时需要知道它在哪个环境中运行。
在过去,我依赖System.Web.Hosting.HostingEnvironment.IsHosted来判断代码是否运行在web服务器上。不幸的是,asp.net核心mvc无法访问System.Web命名空间,因此我需要另一种机制。
如果这些可能性之一是asp.net核心mvc,那么代码如何判断它是否运行在web服务器上?
发布于 2016-04-14 20:06:21
回答我自己的问题,以防对别人有帮助。
有人提到,确定代码是在web服务器上运行还是在桌面应用程序上运行的一种方法是查看它正在运行的进程的名称。这是绝对有可能的,但我几乎无法控制web应用程序的进程名是什么,如果历史有任何迹象的话,名称可能会在未来发生变化。
因此,我选择根据应用程序的配置文件名来确定。这个文件名对于web应用程序和桌面应用程序是不同的,作为一个开发人员,它更受我的控制。
我写的方法是:
public bool IsWebServer {
get {
string file = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile.ToLower();
//web.config used by asp.net 4.X,
//app.config used by MVC Core
//NameOfTheApp.exe.config used by desktop applications
if(file.Contains("web.config") || file.Contains("app.config")) {
return true;
}
return false;
}
}发布于 2016-04-14 14:44:59
不幸的是,目前没有等效的API。当您查看该属性是如何工作的时,您可以轻松地自己做一些类似的事情--而无需假设哪个服务器承载了您的应用程序。
您必须使用静态公共属性设置API:
namespace My.Project
{
public static HostingEnvironment
{
public static bool IsHosted { get; private set; }
public static void SetIsHosted(this IServicesCollection services)
{
// you can grab any other info from your services collection
// if you want. This is an extension method that you call
// from your Startup.ConfigureServices method
IsHosted = true;
}
}
}现在,您可以使用ASP.Net MVC 5和4.5了。您将将其集成到Startup.ConfigureServices()方法中。
public void ConfigureServices(IServiceCollection services)
{
// Set up whatever services you want here.
// Make sure you have your My.Project namespace
// in your using statements so you can use the IsHosted()
// extension method
services.SetIsHosted();
}此解决方案与遗留System.Web.Hosting.HostingEnvironment.IsHosted解决方案之间的唯一区别是,当应用程序由IIS自动启动时,由框架设置标志。这可能与您将要获得的同等解决方案一样接近,同时仍然允许在任何地方托管。
https://stackoverflow.com/questions/36625326
复制相似问题