HttpContext.User NullReferenceException only on deployed server - c#
I am using formsauthentication on my MVC project and when testing locally using the Visual Studio Development Server everything works as expected. Once deployed to IIS 7.5 the HTTPContext.User is causing NullReferenceExceptions.
Both Dev and Prod machines are using the same SQL db (at the moment - this will change post-deployment of course) so I know it is not a problem with the DB or data within.
This must be a setting in IIS or my web.config but I cannot find it.
I've tried various changes to my web.config(from suggestions I've found around SE), here is part of my web.config for the current implementation:
<appSettings>
<add key="autoFormsAuthentication" value="true" />
<add key="enableSimpleMembership" value="false" />
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
****Snip****
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" cookieless="UseCookies"/>
</authentication>
<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.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="ProjectSquid.WebUI.HTMLHelpers" />
</namespaces>
</pages>
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear />
<add name="CustomRoleProvider"
type="Project.Domain.Filters.CustomRoleProvider"
connectionStringName="EFDbContext"
enablePasswordRetrieval="false"
cacheRolesInCookie="true"/>
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="EFDbContext" />
</providers>
</sessionState>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=9" />
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules runAllManagedModulesForAllRequests="false">
<remove name="FormsAuthentication" />
<remove name="DefaultAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="" />
<add name="DefaultAuthentication" type="System.Web.Security.DefaultAuthenticationModule" preCondition="" />
<remove name="UrlRoutingModule-4.0"/>
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" preCondition="" />
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
</modules>
</system.webServer>
What could cause HttpContext.User to differ from the VS Development Server and the IIS 7.5 implementation?
EDIT:
HttpContext is fed through the inherited BaseController:
protected virtual new CustomPrincipal User
{
get { return HttpContext.User == null? null : HttpContext.User as CustomPrincipal; }
}
public new HttpContextBase HttpContext
{
get
{
return ControllerContext == null ? null : ControllerContext.HttpContext;
}
}
The cookie isn't created until the PostAuthenticationRequest:
public void MvcApplication_PostAuthenticationRequest(object sender, EventArgs e)
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
string encTicket = authCookie.Value;
if (!String.IsNullOrEmpty(encTicket))
{
var ticket = FormsAuthentication.Decrypt(encTicket);
var id = new UserIdentity(ticket);
string[] userRole = Roles.GetRolesForUser(id.Name);
var prin = new CustomPrincipal(id);
HttpContext.Current.User = prin;
Thread.CurrentPrincipal = prin;
}
}
}
The authentication itself appears to be working fine as the function causing the exception starts with [Authorize] and successfully begins executing but fails as null when it reaches the first User reference:
int userT = User.Team.TeamId;
In this context the User being CustomPrincipal BaseController.User.
EDIT2:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880"
cookieless="UseCookies"
name=".ASPXAUTH"
protection="All"
slidingExpiration="true"/>
</authentication>
EDIT3
Custom IIdentity:
[Serializable]
public class UserIdentity : MarshalByRefObject, IIdentity
{
private readonly FormsAuthenticationTicket _ticket;
public UserIdentity(FormsAuthenticationTicket ticket)
{
_ticket = ticket;
}
public string AuthenticationType
{
get { return "Custom"; }
}
public bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(this.Name); }
}
public string Name
{
get { return _ticket.Name; }
}
public string UserId
{
get { return _ticket.UserData; }
}
public bool IsInRole(string Role)
{
return Roles.IsUserInRole(Role);
}
public IIdentity Identity
{
get { return this; }
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (context.State == StreamingContextStates.CrossAppDomain)
{
GenericIdentity gIdent = new GenericIdentity(this.Name, this.AuthenticationType);
info.SetType(gIdent.GetType());
System.Reflection.MemberInfo[] serializableMembers;
object[] serializableValues;
serializableMembers = FormatterServices.GetSerializableMembers(gIdent.GetType());
serializableValues = FormatterServices.GetObjectData(gIdent, serializableMembers);
for (int i = 0; i < serializableMembers.Length; i++)
{
info.AddValue(serializableMembers[i].Name, serializableValues[i]);
}
}
else
{
throw new InvalidOperationException("Serialization not supported");
}
}
Custom IPrincipal:
interface ICustomPrincipal : IPrincipal
{
int Id { get; set; }
string Name { get; set; }
string Role { get; set; }
}
public class CustomPrincipal : IPrincipal
{
public CustomPrincipal(UserIdentity identity)
{
this.Identity = identity;
}
public IIdentity Identity { get; private set; }
Most likely, you are attempting to retrieve HttpContext.User before it has been initialized. This behavior differs between IIS Classic (or the Visual Studio Web Server) and IIS Integrated pipeline modes, which would explain why you are seeing different behavior between the environments.
Explanation
HttpContext is part of an application's runtime state. In modern hosting environments (IIS integrated pipeline mode and OWIN), HttpContext is not populated until after the Application_Start method is complete. Any behavior that you have that requires HttpContext.User should not be executed until the Application_BeginRequest event or after.
Reference: Request is not available in this context
It's not clear from your post since configuring the authentication depends on various settings in your project plus the configuration file. For example in Web.config file, there are several places to customize/configure the authentication like this one (the most important rule) that you haven't placed in your post:
<system.web>
<authentication mode="" />
</system.web>
As you know, since the configuration system is based on a hierarchical system of management system that uses **.config* files, you should consider the defaults, perhaps by <remove/> or <add/> some parameters. The configuration files for IIS 7 and later are located in your %WinDir%\System32\Inetsrv\Config folder, and the primary configuration files are:
ApplicationHost.config - This configuration file stores the settings for all your Web sites and applications.
Administration.config - This configuration file stores the settings for IIS management. These settings include the list of
management modules that are installed for the IIS Manager tool, as
well as configuration settings for management modules.
Redirection.config - IIS 7 and later support the management of several IIS servers from a single, centralized configuration file.
This configuration file contains the settings that indicate the
location where the centralized configuration files are stored.
Note: Some settings can be delegated to Web.config files, which may override settings in the ApplicationHost.config file. In addition, settings that are not delegated cannot be added to Web.config files.
Tip: A default installation of IIS 7 does not contain Digest authentication, so adding the settings for Digest authentication to your ApplicationHost.config will have no effect or may cause errors until the Digest authentication module is installed.
You need to see both local and deployment configurations to meet your purpose. If you have trouble with integrated pipeline, see the following pages to take its advantages :
Debugging the IIS7 integrated pipeline with failed request
tracing
How to Take Advantage of the IIS 7.0 Integrated Pipeline
Update About SlidingExpiration : According to MSDN:
Sliding expiration resets the expiration time for a valid
authentication cookie if a request is made and more than half of the
timeout interval has elapsed.
If the cookie expires, the user must re-authenticate. Setting the SlidingExpiration property to false can improve the security of an application by limiting the time for which an authentication cookie is valid, based on the configured timeout value. So I think there's no need to use this as false. This means It will expire cache after time period at the time of activating cache if any request is not made during this time period. This type of expiration is useful when there are so many data to cache. So It will put those items in the cache which are frequently used in the application. So it will not going to use unnecessary memory.
Related
How to allow anonymous authentication for index in owin pipeline?
My index page in a MVC 5 Application return an unauthorized status code. I have configured my application under IIS 10.0 with none authentication to manage the authentication in the owin pipeline : <system.web> <compilation debug="true" targetFramework="4.7.1" /> <httpRuntime targetFramework="4.7.1" /> <authentication mode="None" /> <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" /> <handlers> <clear /> <add name="Owin" verb="" path="*" type="Microsoft.Owin.Host.SystemWeb.OwinHttpHandler, Microsoft.Owin.Host.SystemWeb"/> </handlers> </system.webServer> Here my controller to allow anonymous on index action : [Authorize] public class SPAController : Controller { [AllowAnonymous] public ActionResult Index() { return View(); } } And my owin pipeline where i suspect that i miss something : // Enable static file serving for the current application before authentication phase app.UseStaticFiles(new StaticFileOptions() { RequestPath = new PathString(""), FileSystem = new PhysicalFileSystem(HostingEnvironment.MapPath("~/")) }); Update I also tried this without success : [Authorize] public class SPAController : Controller { [OverrideAuthorization] [AllowAnonymous] public ActionResult Index() { return View(); } } and without attributes
Servicestack SOAP - Invalid credentials returning html in response
In my service, I have a custom auth provider that throws a HttpError if the credentials are invalid like so: throw HttpError.Unauthorized("Invalid Username or Password"); When I access this service via REST and purposely enter invalid credentials, I get the expected response: { "ResponseStatus": { "ErrorCode": "Unauthorized", "Message": "Invalid UserName or Password", } } However, doing the same thing via a SOAP client, I get a Html response from the IIS server: This causes my SOAP client to break as it can't deserialize the response. This can also occur if incorrect data values are included in the request e.g. setting a string value on an integer parameter. The response is fine if an exception occurs in one of my services where I am handling the request (i.e. HttpError.NotFound thrown). I know a similar question has been answered here but it hasn't been updated since 2013. Is there a way to configure the response or override it? Edit 1 I've updated my web.config to look like so (in system.webServer, I had to use "modules" instead of "httpModules".): <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <httpModules> <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" /> </httpModules> <httpHandlers> <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" /> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true"> <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" /> </modules> <urlCompression doStaticCompression="true" doDynamicCompression="false" /> <handlers> <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" /> </handlers> </system.webServer> and my AppHost has the following: SetConfig(new HostConfig { HandlerFactoryPath = "/api" }); SuppressFormsAuthenticationRedirectModule.PathToSupress = Config.HandlerFactoryPath; However I'm still getting the same error as before. I'm wondering if this is due to me passing in credentials as a header with every request rather than specifically authenticating first? It's worth pointing out that this same error occurs when e.g. a string is set on an integer parameter. Edit 2 This solution does in fact work. I was defining the incorrect HandlerFactoryPath: SetConfig(new HostConfig { HandlerFactoryPath = "api" });
The Yellow Screen Of Death is the result of ASP.NET Hijacking the Error Response of Unauthorized Error Responses. You can prevent ASP.NET from hijacking the Error Response with the SuppressFormsAuthenticationRedirectModule. First you need to register the HTTP Module in your web.config: <system.web> <httpModules> <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" /> </httpModules> </system.web> <!-- Required for IIS 7.0 (and above?) --> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <httpModules> <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" /> </httpModules> </system.webServer> next, configure the module with where your API lives - defaults to /api, so in your AppHost Configure: public override void Configure(Funq.Container container) { SetConfig(new HostConfig { HandlerFactoryPath = "api", }); //this is the configuration for Hijacking prevention SuppressFormsAuthenticationRedirectModule.PathToSupress = Config.HandlerFactoryPath; }
HTTP Error 401.0 - Unauthorized IIS 8
Working on a MVC5 project, I have access to the account / login page. When I enter wrong credentials it tells me that the username / password is incorrect. When I enter the right credentials it redirects me to home/index so I assume the login did work. How ever upon getting to the new page I get the following error. HTTP Error 401.0 - Unauthorized. Ant i'm not sure how I would go on and solve this. My Login Controller public ActionResult LogIn() { return View(); } [HttpPost] public ActionResult LogIn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (MembershipService.ValidateUser(model.UserName, model.Password)) { FormsService.SignIn(model.UserName, model.RememberMe); if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return View(model); } And my model public class LogOnModel { [Required] [DisplayName("User name")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [DisplayName("Password")] public string Password { get; set; } [DisplayName("Remember me?")] public bool RememberMe { get; set; } } public interface IFormsAuthenticationService { void SignIn(string userName, bool createPersistentCookie); void SignOut(); } public class FormsAuthenticationService : IFormsAuthenticationService { public void SignIn(string userName, bool createPersistentCookie) { if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); } And last my web.config: <?xml version="1.0"?> <configuration> <connectionStrings> <add name="SaleswebEntities" connectionString= </connectionStrings> <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=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <add assembly="System.Web.Helpers, Version=1.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.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.Helpers" /> <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> <appSettings> <add key="ClientValidationEnabled" value="false" /> <add key="UnobtrusiveJavaScriptEnabled" value="false" /> </appSettings> </configuration> The connection string is not empty, but I did remove it I do not want it posted public.
I've had a simular issue and it were nothing with the code, something did happen with my iis and I had to reinstall it. The key thing here is to make sure you uninstall the Windows Process Activation Service or otherwise your ApplicationHost.config will be still around.
I have noticed that you use FormsService in your Login Controller. I think that this class is SharePoint-specific. I would recommend using WebSecurity.Login() or FormsAuthentication.Authenticate() instead.
Have you checked that your Startup.cs has configured the application correctly? There should be something similar to the following in there: app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } });
Sounds like a IIS permission issue, you should try running VS as administrator if you have not already. " HTTP Error 401.0 - Unauthorized You do not have permission to view this directory or page." Diagnose 401.x HTTP errors on IIS Try to make sure permissions are correct for the folders. Double-click the Authentication feature in IIS. Right-click the "Anonymous Authentication" provider and select edit. Now, right-click the web application in the left pane, select Edit Permissions..., select the Security tab, click Edit -> Add and add IIS APPPOOL\NameOfAppPool. Make sure the Application Pool Identity has read and execute permissions of the folder. Here are a few links. Configuring IIS (Windows 7) for ASP.NET / ASP.NET MVC 3 http://patrickdesjardins.com/blog/asp-net-mvc-http-error-401-0-unauthorized https://serverfault.com/questions/348049/iis-and-http-401-0-unauthorized
MVC 3, Elmah and The view 'Error' or its master was not found
I am working on a legacy website that uses MVC 3, elmah and nhibernate. The Elmah log has literally thousands of " The view 'Error' or its master was not found" errors. I assume that it is covering up the real error. I cannot figure out how to have the real error get logged by Elmah. As a means to attempt to debug, I added - return RedirectToAction("noWhere"); - to force an error. Locally I get a .net screen that simply says "An exception occurred while processing your request..." on staging I get YOSOD screen telling me to set the web.config customerrors node. Both have the customerrors set to on. The web config has the following: <pages> <namespaces> <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.Helpers" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> <httpModules> <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" /> <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" /> <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" /> </httpModules> <customErrors mode="On" defaultRedirect="~/Views/Shared/PageNotFound"> <error statusCode="404" redirect="~/Views/Shared/PageNotFound" /> <error statusCode="500" redirect="~/Views/Shared/PageNotFound" /> </customErrors> The Global.asax has: public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new ElmahHandleErrorAttribute()); } The Elmah class has public class ElmahHandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute { public override void OnException(ExceptionContext context) { base.OnException(context); var e = context.Exception; if (!context.ExceptionHandled // if unhandled, will be logged anyhow || RaiseErrorSignal(e) // prefer signaling, if possible || IsFiltered(context)) // filtered? return; LogException(e); } and the baseController class has: protected ViewResult PageNotFound() { Response.StatusCode = (int)HttpStatusCode.NotFound; return View("PageNotFound", PageViewModelBuilder.UpdateSiteProperties(new PageViewModel())); } protected ViewResult PageBadRequest() { Response.StatusCode = (int)HttpStatusCode.BadRequest; return View("PageNotFound", PageViewModelBuilder.UpdateSiteProperties(new PageViewModel())); } Any help on getting the correct errors to log would be appreciated....
Change "~/Views/Shared/PageNotFound" to "~/Views/Shared/PageNotFound.aspx” (or "~/Views/Shared/PageNotFound.chtml”) in your web.config and make sure you have PageNotFound.aspx in your Shared folder.
Custom handler failing to work due to Request Filtering
This is in IIS express. public class FooHandler : HttpTaskAsyncHandler { public override async Task ProcessRequestAsync(HttpContext context) { var val = await new FooRequest().ProcessRequest(); context.Response.Write(val); } } That s the handler and below is web.config. <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <sessionState mode="Off" /> <compilation debug="true" targetFramework="4.5" /> <machineKey compatibilityMode="Framework45" /> <httpHandlers> <add verb="*" path="*.foo" validate="false" type="FooServer.FooHandler" /> </httpHandlers> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <add name="FooHandler" verb="*" path="*.foo" type="FooServer.FooHandler" /> </handlers> </system.webServer> </configuration> I keep getting the below error. google didnt help. may be you can? HTTP Error 404.7 - Not Found The request filtering module is configured to deny the file extension. Most likely causes: Request filtering is configured for the Web server and the file extension for this request is explicitly denied.