Hugh
Hugh

Reputation: 758

ASP.NET Command Line Arguments

I'm curious about options for passing arguments to an MVC app (web app, rest service etc). There seems to be no support for this from what I can find however...

If I modify an app's Application_Start method (in Globals.asax.cs) and add a statement like this:

Environment.GetCommandLineArgs()

then run this under the Visual Studio debugger, I can see that fours args are being passed.

These are:

A path to the iisexpress.exe file.

A path to an applicationhost.config

A "/site" arg.

A "/apppool" arg.

This suggests that there actually is a way to pass arguments but nobody talks about it and its not documented. I'd like to add another custom arg here that our own code can look for and respond to if it's present.

Upvotes: 2

Views: 4053

Answers (2)

Lex Li
Lex Li

Reputation: 63173

I'd like to simply expand @Steve's comment above.

A typical ASP.NET web app is always hosting by a process. That gives Environment.GetCommandLineArgs a possibility to return you some values as you discovered. However, it would be tricky to pass information via such, as in so many cases you don't have a meaningful way to pass the values you want.

IIS Express in Visual Studio

When you debug a project in VS, it usually runs on IIS Express, and VS does not provide you a place to configure which parameters to pass. (ASP.NET Core projects might be different.)

IIS on Windows Server

When your app finally deploys to a production server, it runs on IIS. IIS worker processes (w3wp.exe) are fully managed by Windows Process Activation Service, so again, you have no way to set which parameters to pass.

Self Hosting

Some project types (ASP.NET Web API/SignalR/WCF) allow you to do self hosting in a console process. You can then process command line parameters in that case.

However, in all, command line parameters are not part of Microsoft's design to pass information to ASP.NET apps. Don't go too far on this path.

Upvotes: 1

John Wu
John Wu

Reputation: 52240

An ASP.NET web site is not a Windows application. It does not have a .exe, for example. Instead, an ASP.NET web site contains a series of classes that conform to a particular interface that are pulled into the IIS process as plugins, in particular a Global.asax that inherits from HttpApplication. When an HTTP request comes in, IIS instantiates the HttpApplication and goes from there; this is not like running a program from the command line.

If you try to learn bits about the application process (e.g. command line arguments) via the various APIs, it is likely you will get information back not about your web site but about the IIS service process as a whole.

It is not possible to provide custom command line arguments to an ASP.NET web site. I would suggest you look into using Environment variables, registry entries, or web.config items instead.

Upvotes: 1

Related Questions