Can I use "HostingEnvironment" to determine if it is Web or Win

In my library, I use HostingEnvironment.MapPath for my web application. But I need to call the same function from windows forms and windows service.

In a Windows application, HostingEnvironment.ApplicationID is null; in a Web application, HostingEnvironment.ApplicationID is something like "99xxx999".

Can I use "HostingEnvironment" to determine if it is Web or Win?

Is it safe to use?

if (HostingEnvironment.ApplicationID == null) { //called from windows application } else { //called from web application } 
+4
source share
2 answers

A more standard way to do this is to use the HttpContext.Current method:

 if (HttpContext.Current == null) { // called from windows application } else { // called from web application } 

Of course, using HttpContext-related materials in non-HTTP layers of your application is a design odor. It doesn't just smell => it stinks.

A more standard way is to have your code passed as an argument directly as an argument. When called from a web application, you must pass Server.MapPath("~/foo.txt") , and when you call it from a Windows application, you must pass the file name relative to the current executable.

Thus, your code should not depend on any specific HTTP data and can be used with pleasure on any platform. The responder must give him the name of the file that your code should process. The way this file is defined is platform dependent. Not responsible for your code. Do not mix duties.

+10
source

Read the msdn documentation here: http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.applicationid(v = vs .100) .aspx

It states:

"The application should work with setting AspNetHostingPermissionLevel to high trust to access the ApplicationId property"

Hope you have your answer.

+3
source

Source: https://habr.com/ru/post/1403456/


All Articles