IIS 7 - Virtual directory redirection path? - iis

I wrote this little web app that lists the websites running on the local IIS + virtual directories attached to the websites.
Using the following line I was able to get the HTTP Redirection URL of a virtual directory, if it was set to redirect:
_directoryEntry.Properties["HttpRedirect"].Value.toString()
Which works quite nicely in IIS 6 - but the value is empty when I try my app in an IIS 7 - and I tried switching the application pool to Classic pipeline as well - what has changed in IIS 7 here? And why?

In IIS7 <httpRedirect> element replaces the IIS 6.0 HttpRedirect metabase property.
You need to set it up like this in your web.config file:
<system.webServer>
<httpRedirect enabled="true" destination="WebSite/myDir/default.aspx" />"
</system.webServer>
If you do not want to tweak web.config, this article talks about a way to do them the IIS 6 way: Creating Http Redirects in IIS7 on Virtual Directories like IIS6
Hope this helps.

What has changed?: IIS7 has a completely new configuration system similar to .NET's hierarchical configuration system. Checkout this link for more detail here on what's changed.
How to get the HttpRedirect value: In C#, rather than using the System.DirectoryServices namespace to access the IIS configuration settings, use the new Microsoft.Web.Administration.dll.
Your code should look something like this example from IIS.net:
using System;
using System.Text;
using Microsoft.Web.Administration;
internal static class Sample
{
private static void Main()
{
using (ServerManager serverManager = new ServerManager())
{
Configuration config = serverManager.GetWebConfiguration("Default Web Site");
ConfigurationSection httpRedirectSection = config.GetSection("system.webServer/httpRedirect");
Console.WriteLine("Redirect is {0}.", httpRedirectSection["enabled"].Equals("true") ? "enabled" : "disabled");
}
}
}
You can actually do quite a lot with the new Microsoft.Web.Administration.dll. Checkout Carlos Ag's blog here for some ideas.
Two quick notes:
Microsoft.Web.Administration.dll is available if the "IIS Management Scripts and Tools" role service is installed. It should be under the inetsrv directory in systemroot.
Any code you run with the MWA dll needs to run as Administrator to access IIS configuration, so just make sure the account running the script has admin rights.
Hope this helps!

Related

Azure does not see Index.cshtml

I'm trying to publish my ASP.NET Core application on Azure service. This works, but when I try to use the application functionality, I get the message
Your App Service app is up and running.
Moreover, in my wwwroot folder I don't have any .html files. I only have an Index.cshtml file, which is located in the Views/Home-folder in my application, all another files are .css, .js, etc.
When I run the application in Visual Studio in Debug mode, immediately opens the page in browser that was generated from Index.cshtml. But after the application is published in Azure, this does not happen.
What can I do to make Azure see Index.cshtml?
AFAIK, a default route would be added to Configure method of your Startup.cs file as follows:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I also created my .Net Core 2.0 MVC application to check this issue, it could work as expected on local side and my azure web app.
Moreover, in my wwwroot folder I don't have any .html files.
Views under Web Application and Web Apllication MVC would be compiled into {your-webapplication-assemblyname}.PrecompiledViews.dll, you could leverage ILSpy to check your DLLs.
For your issue, I would recommend you clear the web content in your web app via KUDU, or modify the publish settings and choose Remove additional files at destination under File Publish Options, then redeploy your application to Azure Web App to narrow this issue.
Are you finding index.cshtml in your web package? In case if you get index.cshtml in your final web package, you may need to add index.cshtml file type to the following in..
..YourAzureWebApp --> Application Settings --> Default Documents
I found out what the problem was. There are two types of applications, as presented below in the picture: Web Application and Web Apllication MVC. I worked with the second type of application. When I selected the first type and published the application, Azure immediately found the required index.html. I just had to choose Web Application.
But why does not it work with the second type of application (Web Apllication MVC)? I still do not know the answer to this question.
2 cents from my side as I just stuck for a while with this.
The problem was that yesterday I'd been playing around with deploying to Ubunut / Ngnix and today I decided to try Azure.
BUT I forgot to comment (disable) the following lines in my Startup:
//for nginx server
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
and that costed me almost half of the day to find the issue.
I also put the routing in the following way
app.UseStatusCodePages();
app.UseAuthentication();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Pages}/{action=Index}");
});
Now looks like it works on Azure :)

Configure Azure Web Sites/Jobs app settings when developing locally

As described in this article: https://azure.microsoft.com/en-us/blog/windows-azure-web-sites-how-application-strings-and-connection-strings-work/, Azure Web Apps/Web Sites/Web Jobs can take their configuration settings (appSettings, connectionString) from environment variables instead of app.config/web.config.
For example, if an environment variable named "APPSETTING_appSettingKey" exists, it will override the following setting from app.config/web.config:
<appSettings>
<add key="appSettingKey" value="defaultValue" />
</appSettings>
This works fine once the application is deployed in Azure, but I would like to use the same method when testing locally.
I tried to emulate this in a local command line:
> set APPSETTING_appSettingKey=overridedValue
> MyWebJob.exe
The web job accesses this setting using:
ConfigurationManager.AppSettings["appSettingKey"]
When running in Azure, it reads the value "overridedValue" as expected, but locally it reads the value "defaultValue" from the app.config file.
Should I expect this to work, or is this implemented only under an Azure environment?
I could obviously create an abstraction over ConfigurationManager that emulates this, but this wouldn't work when calling code that needs a connection string name instead of a connection string value. Also, I want to use the same method regardless of the environment to simplify management of settings.
There are 3 reasons why I need this:
1) I don't like the idea of deploying to production a web.config file that references connection strings, etc for a developement environment, because there's a risk of an error that would cause the development settings (in web.config) to be used in production (production web app connecting to development database, etc), for example if an environment variable is named incorrectly (after renaming the setting in web.config but forgetting to rename it in environment variables)
2) I'm trying to setup development environments where each developer has his own isolated cloud resources (storage account, databases,...). Currently, everyone has to manually edit his .config files to reference the correct resources, and be careful when checking-in or merging changes to these files.
3) A solution can have multiple projects that need to duplicate the same settings (main web app, web jobs, integration test projects,...). This causes a lot of work to ensure updated settings are replicated across all files.
This would be simplified if there was an environment-independent .config file without any actual configuration, each developer would configure a set of environment variables once and be able to use them for all parts of a solution.
Yes, this special transformation of environment variables into config values is done via a component that is specific to Azure WebApps and won't be in play locally.
Generally people are fine with the local behavior this produces - locally you are reading from config settings as usual, but in Azure you're reading from secure settings that were configured via the App Settings portal blade (so these settings aren't in your source code).
You could write an abstraction over this if you wish, E.g. the WebJobs SDK actually does this internally (code here).
When I am developing locally and want to consistantly use Environment.GetEnvironmentVariable. In my static class Main I have the following code:
if (config.IsDevelopment)
{
config.UseDevelopmentSettings();
Environment.SetEnvironmentVariable("UseDevelopmentSettings", "true");
}
Then in my static class Functions I add a static constructor and in there I call the static method below:
static void AddAppSettingsToEnvironmentVariables()
{
String useDevelopmentSettings = Environment.GetEnvironmentVariable("UseDevelopmentSettings"); ;
if (!(String.IsNullOrEmpty(useDevelopmentSettings)))
{
foreach (String key in ConfigurationManager.AppSettings.AllKeys)
{
Environment.SetEnvironmentVariable(key, ConfigurationManager.AppSettings[key]);
}
}
}
The code is small enough that I can simply comment it out before I test in Azure.
If you want to test the application with the value that will be used in Azure portal AppSettings/Connection String. I would recommend use HostingEnvironment.IsDevelopmentEnvironment. To ensure it will work, please change the <compilation debug="true" targetFramework="4.5.2" /> to <compilation debug="false" targetFramework="4.5.2" />. set the value with the same value in Azure portal if (HostingEnvironment.IsDevelopmentEnvironment == false). I have try with a simple project, hope it helps:
public ActionResult Index()
{
if (HostingEnvironment.IsDevelopmentEnvironment == true)
{
ViewBag.Message = "Is development.";
}
else
{
ViewBag.Message = "Azure environment.";
}
return View();
}
Here is the result:

Azure App Service Application Settings Ignored, Using web.config Instead

I recently deployed an ASP.Net Web API project to our Azure App Service test slot but started receiving an error when making requests to the API endpoints. Through remote debugging, it became clear that the app was extracting my dev connection strings from the deployed web.config file.
The connection strings are supposed to come from the Application Settings we set up via the Azure Portal - and, in previous deployments, they were - but that's not the case.
Why would this happen and what can be done to ensure the correct behaviour occurs? We absolutely don't want our production database secrets being put into GIT via the web.config...
I recently experienced the same problem and fixed it:
In Azure App Services, the machine-wide web.config file is located at D:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config.
This file differs to a normal machine-wide web.config file because it has this extra element:
<system.web>
...
<compilation>
<assemblies>
<add assembly="EnvSettings, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
...
</assemblies>
</compilation>
</system.web>
The EnvSettings.dll assembly is located inside D:\Program Files\IIS\Microsoft Web Hosting Framework (unfortunately this directory is access-controlled and I can't get into it).
But EnvSettings.dll is mirrored in the GAC, so I was able to copy it from there.
Inside EnvSettings.dll is an [assembly: PreApplicationStartMethod] attribute that runs a method in EnvSettings.dll which copiesthe APPSETTING_ and database connection-string settings from Environment Variables into the .NET Framework ConfigurationManager.AppSettings and ConfigurationManager.ConnectionStrings collections.
Note this copying only happens once (during application startup), and only in the first AppDomain - so if you have other AppDomain instances in your application they won't see the updated ConfigurationManager.
Therefore, if you see that your Azure Portal configuration settings for your App Service are not being used when you dump your ConfigurationManager, then the following is likely happening:
You used <clear /> in your <compilation><assemblies> element, which stops EnvSettings.dll from being loaded at all.
In which case you need to either add back the <add assembly="EnvSettings... element from above to your own web.config, or find some other way to load it.
I don't recommend saving EnvSettings.dll locally and adding an assembly reference to your project, as EnvSettings.dll is part of the Microsoft Web Hosting Framework.
Or you have code that is clearing or resetting ConfigurationManager after EnvSettings populates it for you.
Or something else is going on that I have no idea about!
As an alternative to having EnvSettings.dll copy your settings over, another option is to copy the environment-variables over yourself - and as you control the code that does this it means you can call it whenever you need to (e.g. if you ever reset them).
Here's the code I used:
public static class AzureAppSettingsConfigurationLoader
{
public static void Apply()
{
foreach( DictionaryEntry environmentVariable in Environment.GetEnvironmentVariables() )
{
String name = (String)environmentVariable.Key;
String value = (String)environmentVariable.Value;
if( name.StartsWith( "APPSETTING_", StringComparison.OrdinalIgnoreCase ) )
{
String appSettingName = name.Substring( "APPSETTING_".Length );
ConfigurationManager.AppSettings[ appSettingName ] = value;
}
else if( name.StartsWith( "SQLAZURECONNSTR_", StringComparison.OrdinalIgnoreCase ) )
{
String csName = name.Substring( "SQLAZURECONNSTR_".Length );
ConfigurationManager.ConnectionStrings.Add( new ConnectionStringSettings( csName, value, providerName: ""System.Data.SqlClient" ) );
}
}
}
}
See my sample here: http://mvc5appsettings.azurewebsites.net/
// My web.config also has a "HERO_TEXT" key in
// that reads "Value from web.config"
string hero = ConfigurationManager.AppSettings["HERO_TEXT"];
Wiki page on App Settings for .NET:
https://github.com/projectkudu/kudu/wiki/Managing-settings-and-secrets
As already mentioned here, make sure you have that App Setting in the right slot.
As I know, the settings in Azure portal will override existing setting in Web.config. So If you want to ignore the Azure Application settings in portal and use Web.config instead. I am afraid you need to configure the settings in web.config, and remove the same key/pair in Azure portal.

IIS 7.5 application pool uses wrong %APPDATA% for custom user as identity

I want my MVC3 web application to access %APPDATA% (e.g. C:\Users\MyUsername\AppData\Roaming on Windows 7) because I store configuration files there. Therefore I created an application pool in IIS with the identity of the user "MyUsername", created that user's profile by logging in with the account, and turned on the option "Load User Profile" (was true by default anyway). Impersonation is turned off.
Now I have the problem that %APPDATA% (in C#):
appdataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
resolves to c:\windows\system32\inetsrv instead of C:\Users\MyUsername\AppData\Roaming.
UPDATE: More exactly, the above C# code returns an empty string, so that Path.GetFullPath(Path.Combine(appdataDir, "MyAppName")) prepends the current path to my application name, resulting in c:\windows\system32\inetsrv\MyAppName.
I know I made this work before with the same web application on a Windows Server 2008 R2, and now I'm getting this problem with the same major version 7.5 of IIS on my Windows 7.
I used the same procedure as before: Created a new user, logged in as that user to create the profile and APPDATA directories, then added the application pool with this identity and finally added the web application to this pool.
Any ideas?
Open your %WINDIR%\System32\inetsrv\config\applicationHost.config and look for <applicationPoolDefaults>. Under <processModel>, make sure you don't have setProfileEnvironment="false". If you do, set it to true.
Application Pools - Your application Pool - Advanced settings ...
Process Model - Load user Profile set True.
It Helps me.
Taken from
https://blogs.msdn.microsoft.com/vijaysk/2009/03/08/iis-7-tip-3-you-can-now-load-the-user-profile-of-the-application-pool-identity/
I experienced the same problem recently. As mentioned by Amit, the problem is that the user profile isn't loaded. The setting is for all application pools, and is in the applicationHost.config (typically C:\Windows\System32\inetsrv\config\applicationHost.config). If you update the applicationPoolDefaults elements as follows, it will work;
<applicationPoolDefaults managedRuntimeVersion="v4.0">
<processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</applicationPoolDefaults>
We've tried this with IIS 7.5, and taken it through to production without problem.
You can automate this if you want;
appcmd set config -section:system.applicationHost/applicationPools /applicationPoolDefaults.processModel.setProfileEnvironment:"true" /commit:apphost
or if you prefer powershell
Set-WebConfigurationProperty "/system.applicationHost/applicationPools/applicationPoolDefaults/processModel" -PSPath IIS:\ -Name "setProfileEnvironment" -Value "true"
Hope this helps
I am experiencing the same problem. Have you by chance installed the Visual Studio 11 beta? I did recently, and I've noticed a couple of differences in how the 4.0 compatible .dlls for that work with our code. I'm still trying to track down the problem for certain, but I didn't have this problem before that.
Edit:
After comparing the decompiled sources from 4.0 and 4.5 for GetFolderPath (and related), there are differences. Whether they are the source of the problem...I'm not sure yet.
Edit 2: Here are the relevant changes. I'm working on trying both to see if I get different results. [code removed]
Edit 3:
I've now tried calling SHGetFolderPath directly, which is what the .NET Framework ends up doing, anyway. It returns E_ACCESSDENIED (-2147024891 / 0x80070005). I don't know what has changed where I'm getting that in some specific cases, but not in others.
Edit 4:
Since you're getting a empty string, you may want to switch your code to use SHGetFolderPath so you can get the HResult and at least know what exactly is happening.
void Main() {
Console.WriteLine( GetFolderPath( Environment.SpecialFolder.ApplicationData ) );
}
[System.Runtime.InteropServices.DllImport("shell32.dll")]
static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, StringBuilder pszPath);
private string GetFolderPath( Environment.SpecialFolder folder ) {
var path = new StringBuilder( 260 );
var hresult = SHGetFolderPath( IntPtr.Zero, (int) folder, IntPtr.Zero, 0, path );
Console.WriteLine( hresult.ToString( "X" ) );
return ( (object) path ).ToString( );
}
The problem is with your IIS settings. The answer is here: Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) returns String.Empty

Install ClientAccessPolicy.xml to Default Web Site using Wix

I'm using Wix to install my web application, and it includes a Silverlight app. Because of cross-domain restrictions, I need to install a ClientAccessPolicy file to ensure that the Silverlight app can talk to the included web services.
Unfortunately, ClientAccessPolicy.xml has to be available from the root of the site, so I can't just place it with my web services or web site. e.g.
Works: http://someserver/ClientAccessPolicy.xml
Doesn't work: http://someserver/MyApp/ClientAccessPolicy.xml
How can I find the directory for the IIS "Default Web Site" to copy the file there as part of the install?
Unfortunately, you have to author a custom action for this. It seems to be just a simple immediate action, which is to find the correct directory path and put it to a property.
UPDATE: The sample C# code for this might look like this:
DirectoryEntry website = new DirectoryEntry(string.Format("IIS://localhost/w3svc/{0}/Root", siteID));
if (website != null)
{
string sitePath = website.InvokeGet("Path") as string;
if (sitePath != null)
{
session["SITE_PATH"] = sitePath;
return ActionResult.Success;
}
}
return ActionResult.Failure;
It assumes that you know the siteID in some way. If it's not always default web site, it is better to let the user choose, for instance. But that's another story.
Note also that this code requires special privileges to access DirectoryEntry - the regular user is not enough.
Hope this helps.

Resources