Add an MVC 2 application to a Nancy site in IIS 7 - asp.net-mvc

In IIS 7, I have created a web site using a Nancy project. Then, I added an MVC 2 application to the site using the alias api. I am able to visit defined routes in the Nancy project perfectly. However, when I visit /api, I get the following error:
Could not load type 'Nancy.Hosting.Aspnet.NancyHttpRequestHandler'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Could not load type 'Nancy.Hosting.Aspnet.NancyHttpRequestHandler'.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): Could not load type 'Nancy.Hosting.Aspnet.NancyHttpRequestHandler'.]
System.Web.Compilation.BuildManager.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase) +11588073
System.Web.Configuration.HandlerFactoryCache.GetTypeWithAssert(String type) +47
System.Web.Configuration.HandlerFactoryCache.GetHandlerType(String type) +18
System.Web.Configuration.HandlerFactoryCache..ctor(String type) +27
System.Web.HttpApplication.GetFactory(String type) +95
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +352
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
It seems that the MVC 2 application is trying to use the NancyHttpRequestHandler to process the request. I say this because routes that are not defined in the Nancy application display a 404 page.
I have tried several things:
To Web.config of the MVC 2 application, I added the following to the <system.web/> block:
<httpHandlers>
<add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpHandlers>
To Web.config of Nancy application, I added the following to the <system.web/> block:
<httpHandlers>
<add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
<remove verb="*" path="api/*" />
</httpHandlers>
I have also tried toying with the settings in the <system.webServer/> and <system.serviceModel/> blocks in both applications.
How can I get the MVC 2 application to behave properly when it is embedded in the Nancy site in IIS 7? Any guidance would be greatly appreciated.

You had the right idea -- you need to block inheritance of the NancyFx specific configuration sections to the child MVC sites.
In your root (NancyFx) site, create a <location/> tag with your normal configuration. Your NancyFx web.config structure will look something like below. (I added comments to try to keep you out of trouble if you decide to upgrade your MVC2 site to MVC3.)
<configuration>
<configSections/>
<!-- FYI... configSections cannot be moved into the location tag. If you plan
to upgrade to MVC3 and use the Razor view engine, those configSection
declarations need to live here. If you upgrade to MVC3 and use the Razor
view engine, you will need to remove the Razor configSections from the
views/web.config files any child MVC3 project. -->
<system.web /> <!-- site-wide system.web settings -->
<system.webServer /> <!-- site-wide system.webServer settings -->
<!-- Put the NancyFx specific configuration here -->
<location path="." inheritInChildApplications="false">
<!-- The inheritInChildApplications attribute is the magic sauce! :) -->
<connectionStrings />
<!-- If the connectionStrings are shared by the child site,
you could move them out to the main configuration. But they
cannot exist in both sections of this file. -->
<appSettings />
<system.web>
<httpHandlers>
<add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
</handlers>
</system.webServer>
</location>
</configuration>

Related

ASP.Net MVC: elmah.axd will be accessible for admin role only

i read this article to implement elmah http://www.c-sharpcorner.com/UploadFile/858292/exception-logging-in-mvc-using-elmah/
but i want only authorized person with admin role can see the elmah.axd file. how could i do it? guide me.
i found one way to attach elmah.axd file with admin role. here is code
https://blog.elmah.io/elmah-tutorial/
<location path="elmah.axd">
<system.web>
<httpHandlers>
<add verb="POST,GET,HEAD"
path="elmah.axd"
type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<authorization>
<allow roles="admin" />
<deny users="*" />
</authorization>
</system.web>
<system.webServer>
<handlers>
<add name="ELMAH"
verb="POST,GET,HEAD"
path="elmah.axd"
type="Elmah.ErrorLogPageFactory, Elmah"
preCondition="integratedMode" />
</handlers>
</system.webServer>
</location>
tell me the above way is the only way to protect elmah.axd file for admin role.
from this link https://blog.elmah.io/elmah-security-and-allowremoteaccess-explained/
i found this one
<appSettings>
<add key="elmah.mvc.requiresAuthentication" value="true" />
<add key="elmah.mvc.allowedRoles" value="Admin" />
<add key="elmah.mvc.allowedUsers" value="Thomas" />
</appSettings>
if i add the above entry in web.config file then no authorized user other than admin role can not access elmah.axd file.......i have doubt. please some one guide me.
As I understand it from the docs, the first example is a general solution for ASP.NET. This has some issues with MVC, specifically with MVC's HandleErrorAttribute as well as getting custom errors.
The second example is for Elmah.MVC, a package specifically catering to ASP.NET MVC. This is the recommended way to set up Elmah when using the MVC framework.
<appSettings>
<add key="elmah.mvc.requiresAuthentication" value="true" />
<add key="elmah.mvc.allowedRoles" value="Admin" />
<add key="elmah.mvc.allowedUsers" value="Thomas" />
</appSettings>
What about ASP.NET MVC?
ELMAH were originally created for ASP.NET. Different features
available in ASP.NET MVC have been causing a lot of head-scratching
since introduced back in 2007. Some of you may have struggled with
MVC's HandleErrorAttribute as well as getting custom errors and ELMAH
working at the same time. In 2011, Alexander Beletsky created the
Elmah.MVC package to help MVC developers using ELMAH. We highly
recommend MVC projects to use this package, since it removes a lot of
the frustrations that people are having with MVC and ELMAH.
https://blog.elmah.io/elmah-security-and-allowremoteaccess-explained/

ASP.NET / MVC: No owin.Environment item was found in the context

I am doing a ASP.NET MVC web application with VS2013. The machine is Windows Server Enterprise, SP2 and IIS 7.
I got the following error:
Server Error in '/' Application.
No owin.Environment item was found in the context.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: No owin.Environment item was found in the context.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: No owin.Environment item was found in the context.]
I googled and found a solution and did something like this (by adding <add name="OWIN".... >) in web.config:
<system.webServer>
<modules >
<remove name="FormsAuthenticationModule" />
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
<handlers>
<add name="OWIN" path="*" verb="*" type="Microsoft.Owin.Host.SystemWeb.OwinHttpHandler" />
</handlers>
</system.webServer>
After doing this, the web app works. However, all the static files such as CSS and Javascript are not found by the browser (404 on all of them), and so my app is style-less.
What is the correct way of configuring
<handlers>
<add name="OWIN" path="*" verb="*" type="Microsoft.Owin.Host.SystemWeb.OwinHttpHandler" />
</handlers>
to get my app work right? Or I need do something else?
Thanks!
I got it working after many tests. Here is what I did:
<add name="OWIN" path="/Account/*" verb="*" type="Microsoft.Owin.Host.SystemWeb.OwinHttpHandler" />
Please note the above path attribute that has a specific path. All my javascript and css files are under other top-level directories.
I am no ASP.NET/MVC expert. If someone has better ideas, please let me know!
Cheers.

return View("myHtmlPage.html") in Asp.net MVC

Masters,
In my MVC application many pages are static (HTML pages).
I've to create both .cshtml and plain HTML pages.
HTML version is also in use by another module.
When I try with return View("Mypage.html") it fails.
Is there any way to consume plain "HTML" pages for my View.
Please help.
What I did in the past was to register ".html" pages to be interpreted as dynamic pages, too. (I.e. just like ASPX).
This can be done through your "web.config" file:
....
<
system.web>
<compilation ...>
<buildProviders>
<add extension=".html"
type="System.Web.Compilation.PageBuildProvider" />
</buildProviders>
....and
....
<system.webServer>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated" />
<add name="PageHandlerFactory-Integrated-HTML" path="*.html"
verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.PageHandlerFactory"
resourceType="Unspecified" preCondition="integratedMode" />
</handlers>
this works well with IIS 7 and IIS 7.5 (and probably on above versions, too). If you are using IIS 6, you have to do it through the IIS Management Console.
Hope this helps..

Why would FederatedAuthentication.WSFederationAuthenticationModule be null in MVC Azure ACS Federated Authentication?

I'm trying to put together FederatedAuthentication with .NET 4.5, MVC 4, and active redirect using a custom server-side login page, using code from this tutorial, and from this code sample.
Redirecting to the LogOn method of my AccountController works fine, and the method looks like this:
public ActionResult LogOn()
{
HrdClient hrdClient = new HrdClient();
WSFederationAuthenticationModule fam = FederatedAuthentication.WSFederationAuthenticationModule; /*** Fails here because this is null **/
HrdRequest request = new HrdRequest(fam.Issuer, fam.Realm, context: Request.QueryString["ReturnUrl"]);
IEnumerable<HrdIdentityProvider> hrdIdentityProviders = hrdClient.GetHrdResponse(request);
ViewData["Providers"] = hrdIdentityProviders;
return View();
}
This fails because FederatedAuthentication.WSFederationAuthenticationModule is null.
Using VS 2012, I've run the new Identity and Access wizard (which seems to replace the old STS dialog). This has given me a folder of FederationMetadata, which appears correct, and several modifications to my Web.Config. In particular, the modules section looks like this:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<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" />
</modules>
And having seen SO answers 8937123 and 8926099, I've added the following as well:
<httpModules>
<add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</httpModules>
And finally my nuget packages config shows Microsoft.IdentityModel, which is correctly referenced by the MVC app:
<packages>
<package id="Microsoft.IdentityModel" version="6.1.7600.16394" targetFramework="net45" />
</packages>
I've also seen this question on social.msdn, which just seems to suggest that the STS dialog does need to be run.
Can anybody explain why FederatedAuthentication.WSFederationAuthenticationModule would be null, and what I can do to stop this happening?
I managed to fix this myself, and since there are a few unanswered questions similar to this on SO, I'll leave the question up and post my own answer.
The issue is to do with upgrading the MVC application to .NET 4.5. Much of the WIF functionality remains the same (at least on the surface), but the classes have all moved to different assemblies. I fixed my problem following the migration guidelines here: http://msdn.microsoft.com/en-us/library/jj157089.aspx
The most important thing is to remove old references to the Microsoft.IdentityModel package (v 3.5.0) and make sure they are replaced by similar references to the System.IdentityModel and System.IdentityModel.Services dlls, which should be version 4.0, and come from the GAC rather than an external package.
My steps to fix were:
Clean out all the junk I'd added to Web.Config and start again with a default MVC Config file.
Remove the Microsoft.IdentityModel package and de-reference the dll
Run the Access and Identity wizard in VS 2012
Duplicate the System.IdentityModel.Services.WSFederationAuthenticationModule reference from <system.webServer><modules> in <system.web><httpModules>
Add <authentication mode="Forms"><forms loginUrl="~/Account/LogOn" /></authentication>
Compile, test, dance little jig of delight...
And this got the original WIF3.5 / MVC3 Code Sample working under.NET 4.5

Why does MvcHttpHandler is mapped from *.mvc?

By default the web.config file for MVC project have the following element:
<handlers>
<remove name="MvcHttpHandler"/>
<add name="MvcHttpHandler" preCondition="integratedMode"
verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler"/>
</handlers>
My problem is that my site returns 404.14, after knocking out all the usual suspects I changed the path (form the snippet above) attribute in the web.config to be "*" and voilĂ ! MVC handler kicks in.
So my question is how does *.mvc even suppose to work? I mean my urls are http://mysite.com/home/index (or even only http://mysite.com/) there is no *.mvc in them.
Am I missing something?
By changing the path you are telling the routing engine to add the .mvc extension to the Url. You probably do not have the .mvc extension mapped in IIS and receive an error.
See here on information about IIS and MVC especially if you are using IIS 6.0:
http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx

Resources