Errors are logged twice when using Elmah with WebApi - asp.net-mvc

I'm trying to log exceptions from my asp.net web api project using elmah. I am having an issue where each error is logged twice.
I am using Elmah.Contrib.Web-Api and my Application class is as follows:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());
RouteTable.Routes.MapHubs();
RouteConfig.RegisterRoutes(RouteTable.Routes);
#if DEBUG
EntityFrameworkProfiler.Initialize();
#endif
GlobalConfig.CustomizeConfig(GlobalConfiguration.Configuration);
}
}
If I commment out the following line then I get no messages at all:
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());
And I can confirm that I am only throwing one error and the call which generates the error is only been called once and I've not manually decorated my controllers or methods with the Elmah Attribute.
To try and resolve this I removed The Contrib Package and added followed the instructions found here http://www.tugberkugurlu.com/archive/asp-net-web-api-and-elmah-integration
This did not solve the issue and it still logs twice. It did allow me to put a break point into the Attribute class and confirm that for each error it is being called twice.
How can I solve this?

What ELMAH-related entries are in your web.config?
I had a similar issue in an MVC application - handled exceptions were being logged twice. In the application I use a custom exception filter to log handled exceptions to ELMAH using error signalling, while the HTTP module takes care of unhandled exceptions.
It turned out that I needed to set:
<add key="elmah.mvc.disableHandleErrorFilter" value="true" />
in web.config in order to disable the built-in exception filter within the ELMAH.MVC NuGet package.
The source code for the built-in filter shows that it logs handled exceptions:
https://github.com/alexanderbeletsky/elmah-mvc/blob/master/src/Elmah.Mvc/HandleErrorAttribute.cs

I'd check your FilterConfig.cs class, it's possible that the default HandleErrorAttribute is being added there and is re-throwing your exception?

For what it's worth, I was having the same problem of ELMAH logging each exception twice in my Web API application (using Elmah.Contrib.WebApi).
Comparing my ELMAH emails against my source history, I was able to identify that the problem started happening after the Ninject.Web.WebApi 3.0.2-unstable-9016 package was installed via nuget.
Sure enough, uninstalling the package and commenting out the single dependency binding that was using it solved the double exception logging problem. Reinstalling the package and leaving the dependency binding commented out caused the problem to start again, so it wasn't the binding itself.
Installing the previous version (Ninject.Web.WebApi 3.0.2-unstable-8) did not cause the problem to happen, but my dependency binding no longer worked.
I'm choosing to live with the problem for the time being.

Have you seen this post ? The author uses an ExceptionFilter to handle logging exceptions

For other folks with the logging twice issue (I don't think this helps the OP?) - this happened to me and the reason was because I had applied the filter globally
GlobalConfiguration.Configuration.Filters.Add(new ElmahErrorAttribute()); //log web api errors
but also applied the attribute to the class (doh!)
[ElmahError]
public class TestController : ApiController
So of course it logged twice.

I had this problem occur only on HTTP 401 responses. The issue turned out to be that Windows Authentication was enabled which was causing the browser to make a second negotiation request.
In my case, I was just able to disable Windows Authentication in the web.config:
<security>
<authentication>
<windowsAuthentication enabled="false" />
</authentication>
</security>
Note: If you don't have the config section unlocked, you can just disable Windows Authentication in IIS.

Related

Stop Elmah logging dynamically in ASP.Net MVC

I have implemented Elmah logging error by using this article in one of my applications and it is running fine as expected.
Now as per the requirements I have to stop logging error dynamically that will handle by the user either user will run logging error or not by simply set in web.config.
But I have no idea how to stop it dynamically and I have also read this article but I am not able to stop logging errors.
Is anything I am missing or I should change?
As suggested in the stackoverflow answer you link to, you can comment out the ErrorLog element from your Web.config. This doesn't disable logging (as suggested by the accepted answer), but switch to using the in-memory logger in ELMAH. This will log all errors in memory, which shouldn't slow down your installation. If you want to remove error logging completely, you can comment out all of the ELMAH-related modules in Web.config.
If you want a toggle, I've described this in my ELMAH Tutorial. Create a new app setting:
<add key="ELMAH:disable" value="false" />
Then add the following code in your Global.asax.cs file:
void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
{
if (bool.Parse(ConfigurationManager.AppSettings["ELMAH:disable"]))
e.Dismiss();
}

How to Show Complex Error Page on Server

I have written an ASP.NET MVC App that is running on a Google Compute Engine. The app is getting a 500 Error on the main Index page that does not occur when running on my local machine.
I am trying to get the complex error page to show from the server, as it is much easier to view them on the web page for hotfixing issues than to delve into the Google Cloud Console to retrieve them. I do not want custom errors, just the same amount of depth that gets shown when running on my local machine.
I have tried:
Removing the existing HTTP Global Filter
Adding <customErrors
mode="Off"/><compilation debug="true"/> to my System.Web in
Web.config
Adding <httpErrors errorMode="Detailed" /><asp
scriptErrorSentToBrowser="true"/> to my System.WebServer in
Web.config
Publishing as debug
Ideas? I'm sure theres a publish setting I'm missing somewhere.
Adding a constructor to the page controller finally provided the detailed error log. If you have taken all of the steps above to get the log, and it still has yet to show, ensure there are constructors for all view controllers involved. Even if the constructor is blank.
I still need to delve into my particular crash issue, but at least I can get an idea where to start.

Facebook C# SDK on ASP.NET MVC 3, Potentially dangerous request

The standard "Potentially dangerous request" is expected, resolve it with [ValidateInput(false)] or something more granular if you wish.
In my case, it happens when I make a call to FbApp.Session. I have a BaseController that all Controllers derive from. In there is an override OnActionExecuting call. Pretty common scenario.
Inside of OnActionExecuting, I use the Facebook C# SDK to manage my use membership. Using if (FbApp.Session != null) is how I check if the user is authenticated.
While running the debugger, it points to the call to FbApp.Session as the source of the exception stating "A potentially dangerous request...", due to HTML in one of the posted request vars - even though the actual action I'm posting to has [ValidateInput(false)] attribute.
What is going on inside the Facebook C# SDK that would cause this behavior? How can this be resolved?
Edit: looks like this could be a bug in ASP.NET MVC 3 RC2 (I haven't upgraded to full release yet). I'll upgrade and report my findings.
The answer is, make sure you're on ASP.NET MVC3 RTM, and have <httpRuntime requestValidationMode="2.0" /> in web.config.

ASP.NET: This method cannot be called during the application's pre-start initialization stage

I'm trying to get an ASP.NET MVC 3 site running on IIS 6.0.
Currently when I request a page from the server it gives the following error:
Parser Error Message: This method cannot be called during the application's pre-start initialization stage.
on this line:
<add name="MyMembershipProvider" type="NS.MyMembershipProvider" connectionStringName="MyDatabase" applicationName="/MySite"/>
I'm completely stumped and don't have much of a clue about the ASP.NET application lifecycle, let alone the differences between 6.0 and 7.0. Reading through the MSDN pages on it hasn't seemed to help much.
Does anyone have any insight or any good links for investigation? :)
Add this in your web.config (in the appSettings section):
<add key="enableSimpleMembership" value="false"/>
<add key="autoFormsAuthentication" value="false"/>
EDIT:
For the ones who ask why, it is a known issue described in the mvc 3 release notes
More details here
After upgrading some of my applications from ASP.NET MVC3 to MVC4 I was getting this error. It was a result of the WebMatrix assemblies (WebMatrix.WebData.dll and WebMatrix.Data.dll). I removed those references and assemblies from the /bin directory and that took care of the issue.
#Ek0nomik is right. We migrated from the MembershipProvider to the new ExtendedMembershipProvider allowing us to take advantage of some of the new functionality offered in the WebMatrix namespace. By default Simple Membership is enabled for some reason so we had to disable it explicitly since we didn't want to go as far as using the SimpleMembershipProvider.
All we had to do was add this to the web.config:
<add key="enableSimpleMembership" value="false"/>
Having Simple Membership enabled caused the Provider initialisation code to execute before the Application_Start handler. Our app structure requires App_Start to be the first thing to execute. Personally I would always expect this but Simple Membership changes this behaviour. Beware.
Well, I just got this error, and it resulted from having accidentally copied a .cshtml into the root of my project. It wasn't even included in the project. Deleted that and the error went away. This was with MVC3 on IIS7. I imagine some of the people getting this problem are in the same boat.
This is caused by any of a number of Reflection calls being made too early in an Application. It just so happens the Web.Config suggestions in other answers prevented one such Reflection call from being made. In my case however:
I'm using Entity Framework, and ran update-database. I got:
This method cannot be called during the application's pre-start initialization phase.
As it turns out we had code that used a library which was recently modified to get all code in all namespaces/projects. Specifically, it called:
System.Web.Compilation.BuildManager.GetReferencedAssemblies()
Kaboom. That caused this obscure error. EF Migrations run in a weirdo zone where the application is half running and half not, meaning the above method can never be called by any code Migrations would call on.

How to catch error in an ASP.NET MVC and display a gracious error message to the user?

I'm writing a very small application for my organization. As nobody seems to know what he wants, I've decide that I'll deploy a demo on our local server so people can get ideas on how to conceive the big thing.
Now here's the problem: While developing on my laptop, when the application crashes, I get a yellow screen giving feedback on the problem (to me). But, if I decide to put the application online, I don't want those kind of yellow screen to be seen by others who are not developers (I know they might be a few because the demo is just a starting point).
Is there anyway I can put a mechanism in place so that when there's an fatal error, the user can get a nice screen telling with an e-mail link telling him to send me an e-mail?
Thanks for helping
I'd recommend wiring ELMAH in your project, and adding the custom errors tag the other answers pointed to. This way you have a user-readable error page and full error tracing at your fingertips. You can also configure elmah to automatically send you an email with the details. The user doesn't even need to know it happened...
Priceless!
Use the customErrors section of then root web.config to specify how your application handles errors.
In your case I would think that you would want to set this to RemoteOnly so that you can still see the errors on your local machine and set 500 errors to go to your contact form:
<configuration>
<system.web>
<customErrors defaultRedirect="Error.htm" mode="RemoteOnly">
<error statusCode="500" redirect="ContactAdmin.htm"/>
</customErrors>
</system.web>
</configuration>
Similar to classic ASP.NET by using customErrors
I would say the quick fix is to use try catch blocks. When you catch an error, send the user to a custom error controller and action. On this action you could have a form for them to email you... and in hidden fields you could have the exception, because you passed it to the action.
try
{
int myvar = 0/4;
}
catch(Exception exceptionObject)
{
return RedirectToAction("HandledExceptionAction", "ErrorController", exceptionObject);
}
Have a look at this I'm sure it'll solve all your problems.
http://blogs.microsoft.co.il/blogs/shay/archive/2009/03/06/real-world-error-hadnling-in-asp-net-mvc-rc2.aspx

Resources