Issue: creating AD FS claims aware application in Visual Studio 2013 - asp.net-mvc

I am new to trying to use AD FS and I have been running in circles.
Trying to make a claims aware application
The organization handles its own authentication
I have gotten my test application to verify authentication but it seems wrong.
Create new application in Visual Studio
Choose Web -> Visual Studio
Choose .Net Framework 4.5
Select ASP.Net MVC 4 Web Application
Add Reference to System.Identity
Add Reference to System.Identity.Services
Edit my web.Config file
in the configsection -- add the following
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
then add
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:FederationMetadataLocation" value="https://fedtest.xxxxxxxx.com/FederationMetadata/2007-06/FederationMetadata.xml" />
<add key="ida:Realm" value="https://myappNameHere.xxxxxx.com" />
<add key="ida:AudienceUri" value="http://myappNameHere.xxxxxxx.com" />
<add key="loginUrl" value="~/Home" />
</appSettings>
Then add
<location path="Home">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<location path="Logout.html">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Then add
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authorization>
<deny users="?" />
</authorization>
<authentication mode="None" />
</system.web>
Then add
<identityConfiguration>
<audienceUris>
<add value="http://myappName.xxxxxx.com/" />
</audienceUris>`
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="http://fedtest.xxxxxxx.com/adfs/services/trust">
<keys>
<add thumbprint="12345567890asdasfsdgdfhdfgjdf123124" />
</keys>
<validIssuers>
<add name="http://fedtest.xxxxxxxx.com/adfs/services/trust" />
</validIssuers>
</authority>
</issuerNameRegistry>
<securityTokenHandlers>
<add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
<certificateValidation certificateValidationMode="None" />
</identityConfiguration>
</system.identityModel>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="true" />
<wsFederation passiveRedirectEnabled="true"
issuer="https://fedtest.xxxxxxxxx.com/adfs/ls/"
realm="https://myappName.xxxxxxxx.com/"
reply="https://myappName.xxxxxxxxx.com/"
requireHttps="true" />
</federationConfiguration>
</system.identityModel.services>
Why do I think all this is wrong?? Well I got all those lines of web.config from the following steps...
go back to step 5 and do the following
Under Tempalte click web
chose the only option --- ASP.NET Web Application
Wizard comes up and click the 'change Authentication'
Choose Organizational accounts
change drop down to 'On Premises'
fill out 'On-Premises Authority'
Fill out 'App ID URI'
Look at web.config
But using the application that those steps produce will create a redirect loop that I have never been able to trouble shoot.
So -- suggestions on what I am doing wrong. It can't be considered right to generate the web.config in a standard way and paste it into a previous version to get it to work.

Refer: Use the On-Premises Organizational Authentication Option (ADFS) With ASP.NET in Visual Studio 2013.
In terms of the redirect loop. the usual reason is that for your ADFS RP, you configured the endpoint without a trailing slash.
Add the missing "/" and ensure it matches the string in your web.config.

Enable SSL in your application and set the SSL URL as the default in your web properties.

Okay -- what the answer ended up being...
1) I started down this route because i kept getting a redirect loop that I thought was caused by the web.config.
It wasn't the web.config.
2) So create the the application as you are supposed to in VS 13 -- namely go to c# -> web -> and then click the ASP.NET Web Application and set up the on premise authentication
3) My redirect loop was caused by multiple LDAP claims bundled together coming from AD FS
4) Sent my claims one rule at a time and worked like magic.
If anyone can shed light as to why this should be true I am curious.

Related

IIS ASP.NET - URL Rewrite - FormsAuthentication module fires before RewriteModule module

I have one site and 3 applications in 3 virtual folders and 3 app pools.
I use URL rewrite (redirect or rewrite doesn't matter) to catch some wrong urls and rewrite or redirect to appropriate application.
All 3 apps are asp.net MVC and use Forms Auth.
They must use sepparate app pools.
If I use rewrite I have an error that URL can't be served from same app pool, so rewriting doesn't work across app pools, that is a known issue.
If I use redirect there is a problem that before I can issue a redirect from URL rewrite FormsAuth sends redirect for login.
This is scenario where I am already logged in in app1, but I want to redirect from app2 and app2 has no session yet and it redirects me to login of app2 instead that I get URErewrite/redirect to URL in app1.
Can this be overridden ?
So that URL Rewrite redirect is not surpassed with FormsAuth redirect.
I tried to put RewriteModule in front of FormsAuthentication module in main applicationHost.config (C:\Windows\System32\inetsrv\Config) but it doesn't work :
<modules>
<add name="IsapiModule" lockItem="true" />
<add name="IsapiFilterModule" lockItem="true" />
<add name="HttpLoggingModule" lockItem="true" />
<add name="HttpCacheModule" lockItem="true" />
<add name="StaticCompressionModule" lockItem="true" />
<add name="DefaultDocumentModule" lockItem="true" />
<add name="DirectoryListingModule" lockItem="true" />
<add name="ProtocolSupportModule" lockItem="true" />
<add name="HttpRedirectionModule" lockItem="true" />
<add name="StaticFileModule" lockItem="true" />
<add name="AnonymousAuthenticationModule" lockItem="true" />
<add name="WindowsAuthenticationModule" lockItem="true" />
<add name="RequestFilteringModule" lockItem="true" />
<add name="CustomErrorModule" lockItem="true" />
<add name="FailedRequestsTracingModule" lockItem="true" />
<add name="ConfigurationValidationModule" lockItem="true" />
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule" preCondition="managedHandler" />
<add name="RewriteModule" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="managedHandler" />
<add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" preCondition="managedHandler" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
<add name="DefaultAuthentication" type="System.Web.Security.DefaultAuthenticationModule" preCondition="managedHandler" />
<add name="RoleManager" type="System.Web.Security.RoleManagerModule" preCondition="managedHandler" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" preCondition="managedHandler" />
<add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" preCondition="managedHandler" />
<add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule" preCondition="managedHandler" />
<add name="Profile" type="System.Web.Profile.ProfileModule" preCondition="managedHandler" />
<add name="UrlMappingsModule" type="System.Web.UrlMappingsModule" preCondition="managedHandler" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="managedHandler,runtimeVersionv4.0" />
<add name="ScriptModule-4.0" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler,runtimeVersionv4.0" />
<add name="ApplicationRequestRouting" />
</modules>
</system.webServer>
UPDATE ::::::::::::::::::
I didn't find out a way to overide FormsAuth so I went the ARR route.
I have 4 sites (no more one site and 3 apps/virtualFolders) :
*_ARR site listens to real ip and virtual host, it is empty , it only has URL rewrite rules, so it is guaranteed that URL rewrites are executed before everithing, the problem of Rewriting to another APP pool is solved by ARR reverse proxy, URL Rewrice at the end causes local reconnection ala reverse proxy, there aro no server farms configured in ARR, only one checkbox (enable proxy).
Other three sites keep 3 versions of app.
There is a file that keeps a record which version is the last installed.
There is a cookie issued for affinity to site/version of app.
All that is handled in custom URL revrite provider.
Cookies with this solution :
Cookie basicaly has the port writen inside. So URL rewrite sends the user to correct version.
And new logons go to newest version, allready logged in user stays at his current version, and finnaly it works as it needs to work.
All this because as I said before , objects in our Session can't be serialized.
And for existing loggins there is no performance hit in starting up site.

User not recognized as logged in when application is run as Start Without Debugging, user authentication works perfectly when run as Start Debugging

I've built a small ASP.NET web application in Visual Studio 2019, starting from the ASP.NET MVC web application project template for VB, which uses the default Individual User Accounts for authentication. I'm nearing the end of development, and somewhere along the way I lost the ability to log in to my application when I run it without the debugger attached via CTRL-F5: Start Without Debugging. Running the application with the debugger attached via F5: Start Debugging and any other run method that attaches the debugger allows the application to behave as expected.
On startup, the web application asks the user to log in. After a successful login, the expected behavior is a redirect to the home page, but currently a successful login only shows the login page again, and I believe the application doesn't recognize the user as authenticated.
I started debugging with the old clean, recompile, and rebuild and didn't have any luck there. Added a throw statement inside the login method's success statement and verified that the login attempt does succeed. The login method with this throw statement (located in AccountController.vb) is shown below. The sign in attempt does trigger the SignIn.Success case.
' POST: /Account/Login
<HttpPost>
<AllowAnonymous>
<ValidateAntiForgeryToken>
Public Async Function Login(model As LoginViewModel, returnUrl As String) As Task(Of ActionResult)
If Not ModelState.IsValid Then
Return View(model)
End If
' This doesn't count login failures towards account lockout
' To enable password failures to trigger account lockout, change to shouldLockout := True
Dim result = Await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout := False)
Select Case result
Case SignInStatus.Success
Throw New System.Exception("Sign In Succeeded") 'Throws both with and without the debugger attached
Return RedirectToLocal(returnUrl)
Case SignInStatus.LockedOut
Return View("Lockout")
Case SignInStatus.RequiresVerification
Return RedirectToAction("SendCode", New With {
returnUrl,
model.RememberMe
})
Case Else
ModelState.AddModelError("", "Invalid login attempt.")
Return View(model)
End Select
End Function
Strangely, the inability to log in persists even if I remove the only two <Authorize> attributes in the project, which I thought would do away with the log in screen all together. (They're attached to the AccountController and ManagerController classes, and their placement matches other projects I've completed in the past using the same project templates)
One of the only related internet resources I could find is this SO question. I'm both building and deploying to targetFramework 4.7.2, and my web.config file was generated by the project template except for the database connection string, but I've included it just in case someone spots something awry.
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=my secret token" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=very secret connection string"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
<roleManager enabled="true" defaultProvider="MySqlRoleProvider">
<providers>
<add name="MySqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
applicationName="RFIDDataEntry"
connectionStringName="DefaultConnection"/>
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
....
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
TLDR: My VB.NET web application doesn't recognize a user as logged in when the application is run without the debugger attached, even though the login attempt succeeds.
I also faced same issue last few days. My browser is Edge Developer. After removing .vs folder the problem persist. Then I remove all cache from browser and Voila, problem solved.
I was able to resolve this issue by deleting the .vs folder.

Azure Active Directory disable while developing localhost

Is there a way to disable or bypass Azure Active Directory while I'm developing my application? I've tried the following and it still redirects to AAD for authentication.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//IdentityConfig.ConfigureIdentity(); commented out for dev. 12/12/2014
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
//private void WSFederationAuthenticationModule_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
//{
// if (!String.IsNullOrEmpty(IdentityConfig.Realm))
// {
// e.SignInRequestMessage.Realm = IdentityConfig.Realm;
// }
//}
I commented out the methods in the IdentityConfig.cs, still redirects to AAD.
Advice is much appricated.
This is my web.config:
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ida:FederationMetadataLocation" value="https://login.windows.net/accountname.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml" />
<add key="ida:Realm" value="https://accountname.onmicrosoft.com/application.WebUI" />
<add key="ida:AudienceUri" value="https://accountname.onmicrosoft.com/application.WebUI" />
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=accountname;AccountKey=+mykey==" />
</appSettings>
<system.webServer>
<modules>
<add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.WebRequestTrackingModule, Microsoft.ApplicationInsights.Extensibility.Web" preCondition="managedHandler" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="true" />
<wsFederation passiveRedirectEnabled="true" issuer="https://login.windows.net/onalabama.onmicrosoft.com/wsfed" realm="https://onalabama.onmicrosoft.com/Procurement.WebUI" requireHttps="true" />
</federationConfiguration>
</system.identityModel.services>
This solution is not very general, but might be just want you want if you are deploying to Azure Web Sites. You can ask Azure Web Sites to enforce authentication with an AAD before allowing users to reach your site.
Basically, you can develop locally WITHOUT any AAD in your code, and deploy that way too. Authentication is instead configured for the Azure Web Site - no code needed - after you configure it on the CONFIG tab in the Azure portal.
Here is a nice writeup: http://azure.microsoft.com/blog/2014/11/13/azure-websites-authentication-authorization/
There are some current limitations (see the article), but I've found this handy in a few situations already.

Problem running MVC3 app in IIS 7

I am having a problem getting a MVC 3 project running in IIS7 on a computer running Windows 7 Home-64 bit. Here is what I did.
Installed IIS 7.
Accessed the server and got the IIS welcome page.
Created a directory named d:\MySite and copied the MVC application to it. (The MVC app is just the standard app that is created when you create a new MVC3 project in visual studio. It just displays a home page and an account logon page. It runs fine inside the Visual Studio development server and I also copied it out to my hosting site and it works fine there)
Started IIS management console.
Stopped the default site.
Added a new site named "MySite" with a physical directory of "d:\Mysite"
Changed the application pool named MySite to use .Net Framework 4.0, Integrated pipeline
When I access the site in the browser I get a list of the files in the d:\MySite directory. It is as if IIS is not recognizing the contents of d:\MySite as an MVC application.
What do I need to do to resolve this?
As requested, here is the web.config:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I posted this question on "ServerFault" as well and got a resolution to the issue here.
The answer is:
Since IIS was installed after .NET 4, you likely need to run the aspnet_regiis.exe tool to register all the .NET 4 stuff with IIS.
I like to add some details:
After registering ASP.NET 4 using aspnet_regiis -i I also had to update the web application using aspnet_regiis -s W3SVC/1/ROOT/SampleApp1 in order to fix the problem.
The /1/ in W3SVC/1/ROOT/SampleApp1 is the instance of your web application. You can find it by looking into your IIS Manager in the column ID.
The ROOT/SampleApp1 in W3SVC/1/ROOT/SampleApp1 is your application path. If you want to update all sites, just do aspnet_regiis -s W3SVC/.
Afterwards it worked fine for me.
I had 403.14 errors when running an MVC 3 website on the server. Server was 32 bit. 2008. IIS7. The problem was that the HTTP Redirection feature was not installed. Server Manager -> Roles -> Web Server -> Roles Services -> HTTP Redirection. This is the only thing that fixed it for me. The web.config needed no change.
I think the majority of IIS7 website setup problems is due to folder security. If you try to create a website by copying the application folders directly from your dev environment to a folder not under wwwroot, the security on your folders will be wrong and you will fight it for hours getting ambiguous errors. The EASY way to get it correct, is to inspect and inetpub/wwwroot folder, examine it and add permissions to your folder, starting with computername\IIS_IUSRS and computername\Users. For mvc, make sure you have a web.config AND global.asax at the root. You do not need a default document for mvc and you should not allow directory browsing. If using aspnet_regiis, you may want to use the -ir if there are other sites being hosted on the machine.
Have you checked the websites default document in IIS is at the top of the list.
I think it defaults to default.asp with default.aspx either not there or at the bottom of the list
I didn't solve this problem until I install .net v4.0.30319 ,before that .net version on my machine is v4.0.30128 . It takes me a long time to figure out the problem,hope this can help someone.

Getting an ASP.MVC2/VS2010 application to work in IIS 7.5

I've recently downloaded beta 2 of VS2010 and started playing with ASP.NET MVC2. Initial development was done with Casini, but now I wanted to run the application from IIS 7.5 (I'm running Windows 7).
I've installed the IIS6 metabase compatiblity and I run VS2010 as administrator so I can use the "Create Virtual Directory" button from the "Web" tab of the project settings.
This created the web application entry in IIS, but it doesn't work.
When I go to the main page (http://localhost/MyMvcApp/) I get a HTTP 403 error. When I go directly to one of the sub-pages (http://localhost/MyMvcApp/Home/) I get an HTTP 404.
So I guess for some reason the URL routing isn't working.
I've already added UrlRouting as a module and a handler to the web.config. In my searches this is offered as a solution for some similair problems. But for me this still doesn't work.
The interesting part of my web.config looke like this:
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
<httpHandlers>
<add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler" />
</httpHandlers>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>
<handlers>
<remove name="MvcHttpHandler" />
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler" />
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
<httpErrors errorMode="Detailed" />
</system.webServer>
I've just had this problem, and unfortunately the fix here didn't work for me.
What did work was running this:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
in a command window...works like a dream now!
(So, is ASP.Net not installed into IIS by default when you install VS2010?)
After more checking and trying I noticed in the "Turn Windows features on or off" dialog that "HTTP Errors" and "HTTP Redirection" were missing.
This is strange because as far as I can remember this was installed automatically by the Microsoft Web Platform Installer.
In any case "HTTP Redirection" seemed like a need-to-have feature when working with MVC. So after I installed it everything seemed to work perfectly.
Add this to your web.config file:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!-- rest of config -->
</system.webServer>
It is such a pain doing this manually. But definitely doable! I managed it and summed it up in this step by step guide on adding an mvc 2 project to an exisitng web forms solution here. Hope this helps... it took me ages to work though all the config settings and there seem to be so few resources on the subject.
Please note that you must run aspnet_regiis.exe -ir as administrator, it seems obvious but when you are tired of trying things with no success to solve that, you could pass it.
Just to say a big THANK YOU to all the responses, after many hours trying different things, finally I could get work my MVC 2 app in IIS.
What Helped to me is using classic pipeline for AppPool instead of integrated:
I was building an MVC2 application on my laptop Windows 7, using .net beta 2 and
VS 2010 beta 2. When I installed the entire development environment on Windows Server 2008, including VS, built the solution and ran it, the routing worked fine.
The next step was to create a production server on Windows Server 2008, on which I deployed the .net 4.0 beta but none of the other stuff which came with the VS 2010 beta download.
Under this configuration the routing never worked until I enable HTTP Redirection as indicated by Jeroen.
Hope this helps someone who might be in the same boat.
Just wanted to note that I was having the same problem with 403 and 404s but adding the system.webServer and all the elements from the system.web/pages/namespaces node resolved it for me.

Resources