How to find out if the current application is an ASP.NET web app

后端 未结 4 1115
Happy的楠姐
Happy的楠姐 2021-02-01 08:05

From a managed class library, I\'d like to find out whether the currently executing application is an ASP.NET web application (web forms or MVC) or not.

I have seen diff

4条回答
  •  有刺的猬
    2021-02-01 08:27

    Potentially Not reliable. MSDN implies that this will always return a new object if one does not exist already. Thus there are technically times where you can call it and have one not exist before it is called.

        System.Web.Hosting.HostingEnvironment.IsHosted == true
    

    All web environments need a context. What handler is inside that context is what tells you the type of web environment. (MvcHandler for example). Note this can be different types of handlers for the same environment - You can run MVC and web forms together for example. It just depends on what is currently being served and the pipeline it is using.

        System.Web.HttpContext.Current != null
    

    All web apps need an application ID. It is unique and does not change as application pools are restarted.

        System.Web.HttpRuntime.AppDomainAppId != null
    

    I've never seen this, though just logically I can imagine a time where the cache is not used and thus wouldn't be reliable.

        System.Web.HttpRuntime.Cache != null
    

    You're right.

    checking for a web.config file (note: I don't think this is reliable)

    I use something of this sort within a library. I've found it reliable.

             Page page = (HttpContext.Current != null && HttpContext.Current.Handler != null) ? HttpContext.Current.Handler as Page : null;
             if (HttpRuntime.AppDomainAppId != null && page != null)
             {
                //I'm a web forms application
             }
             else if (HttpRuntime.AppDomainAppId != null && page == null && HttpContext.Current != null) { throw new InvalidOperationException("I'm an MVC application"); }
             else throw new InvalidOperationException("Im not ASP.Net web");
    

提交回复
热议问题