I have a project mvc4 web application. it is a chat application where users authenticated to chat in private room and can be not authenticated for public chats.I have elmah.axd package in my project to log all errors and it logs the "The connection id is in the incorrect format." error from signalR, every time user authenticated LogIn and LogOut. is there a way to catch it and not log it ?
You tagged Elmah as your error reporting tool, so:
https://code.google.com/p/elmah/wiki/ErrorFiltering
To add an exception filter programmatically, put the following in your Global.asax file (or in the code-behind file):
// Don't forget to reference the Elmah assembly and import its namespace.
void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
{
if (e.Exception.GetBaseException() is HttpRequestValidationException)
e.Dismiss();
}
Related
How to get caller IP addres in ASP.NET MVC4 Global.asax.cs Application_Start event ?
HttpContext.Current.Request object is not available there.
Thread.CurrentPrincipal.Identity exists.
I want to log user name and IP address which were used to start application.
MVC4 application runs in Windows and in Mono
As you can see by the ASP.NET Lifecycle on MSDN, the Application_Start event not only happens long before the AcquireRequestState event where the request object is built, it is also done out of band with the request lifecycle altogether. In other words, Application_Start occurs only once when the application starts or when the application pool recycles, not once per request.
So, the answer to your question is simply that you can't do that (unless of course you set a static variable in the Application_Start event and use either Application_BeginRequest as in Darin's answer or an MVC filter to actually do the logging).
But MVC includes authorization filters and action filters which are meant for implementing cross-cutting concerns such as logging and/or auditing of the current user's IP address. Authorization and action filters do not run until after the request object has been created.
The HttpContext is not available when the application starts. You could achieve that in the BeginRequest method in your global.asax:
private static bool initialized = false;
private static object syncRoot = new object();
protected void Application_BeginRequest()
{
if (!initialized)
{
lock (syncRoot)
{
if (!initialized)
{
// do your stuff with the user IP getting from the current context
initialized = true;
}
}
}
}
I am trying to log the entire exception to the IIS log in the following way:
public void OnTransientFaultOccurred(object sender, RetryingEventArgs e)
{
_httpResponse.AppendToLog(string.Format("RetryCount:{0}", e.CurrentRetryCount));
_httpResponse.AppendToLog(string.Format("NextRetryIn:{0}ms", e.Delay.TotalMilliseconds));
_httpResponse.AppendToLog(string.Format("Exception:{0}",e.LastException));
}
But the log only shows '...'.
Is there any limit in terms of how much data can be written to the log ?
One thing to try: Make sure the advanced logging extension is enabled.
As per Append custom value to IIS logs from ASP.NET.
I created a new asp.net web application using the template that visual studio has. That type of project create a login out-of-the-box which I configured with the aspnet_regsql command to work with my database.
Now, when someone logs into the application, I need to know whether or not the login was sucessful, so I can save in Session[''] the user name among other things.
I was expecting to find a method that returns true or false but instead in the Login.aspx.cs is just the Page_Load method and I don't understand how it works.
I tried associated a onclick method that get the value of the UserName control, but obviously, that only works when the user log in for the first time, if the user check "Remember me next time" it won't work.
The AuthenticateRequest event is raised when the user has been authenticated, however in this event you do not have access to the SessionState yet. Therefore, to save the Session you should consider the PostAcquireRequestState application event.
ASP.NET Application Life Cycle Overview for IIS 7.0
ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0
For additional info:
AuthenticateRequest event
Example:
In global.asax
void Application_PostAcquireRequestState(object sender, EventArgs e)
{
if (Context.Session != null)
{
Application.Lock();
Session["user"] = User.Identity.Name;
Application.UnLock();
}
}
Additionally, if you are using the LoginControl, you can handle the LoggedIn event:
ASPX
<asp:Login runat="server" ID="login" DestinationPageUrl="~/Default.aspx"
FailureAction="RedirectToLoginPage"
onloggedin="login_LoggedIn" ...>
....
ASPX code behind
protected void login_LoggedIn(object sender, EventArgs e)
{
// set the Session here
}
The aspx web project template makes use of the asp:Login control, which does the authentication for you.
If you need to customize the login, you can roll your own username / password inputs, and then call the membership API directly, e.g.
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.SetAuthCookie(username, rememberMe);
// Do your custom stuff here
...
You can also check to see whether the user is authenticated by using
UserPrincipal.Identity.IsAuthenticated
See MSDN for more details
I made really basic facebook application, which collect permission from user to post data. Some time ago (around New year) it worked fine.
I am using http://facebooktoolkit.codeplex.com, and my code looks like this:
public partial class Facebook : CanvasFBMLBasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if(this.Api.Users.HasAppPermission(global::Facebook.Schema.Enums.ExtendedPermissions.publish_stream))
And at this moment I am having exception: parameter uid or session key required
As i understand, I should have some session defined by Facebook and CanvasFBMLBasePage should parse it, and make it possible to use application, but this is not happening.
My application settings (maybe I mis something):
Canvas Callback URL: http://www.domain.com/app/action/facebook.aspx?
Render Method: FBML
Also, I put my IP in server whitelist.
Thanks for help
Have you called the "ConnectToFacebook" method in the api before calling "HasAppPermission"?
I am developing an ASP.NET site with C# on IIS 7, but I hope for an answer that will apply to IIS 6 as well. Part of this site is the ability to upload up to 5 images at a time. I have a nice algorithm to resize the image that is uploaded to my optimal size and ratio.
So the only real size limitation I have is during the initial upload. I have modified my web.config to raise the packet limit from 4MB to 32MB. For the most part this takes care of my issues.
My question comes in the rare cases that a user tries to load more than my limit. I can raise the limit, but there is always a chance a user can find 5 files that are bigger. If a user selects files that are bigger, my try/catch block does not handle the error. The error is coming from IIS.
So how can I catch the error in C# code where I can make modifications to my ASP.NET interface to inform the user to select smaller files instead of them seeing a nasty error screen?
You can get access to the exception when the request length is exceeded. Use an HttpModule, and add a handler for the Error event.
The exception is of type: System.Web.HttpUnhandledException (with an InnerException of type: System.Web.HttpException).
To catch this exception, add this to your web.config:
<httpModules>
<add name="ErrorHttpModule" type="ErrorHttpModule"/>
</httpModules>
And add this class to your App_Code folder:
public class ErrorHttpModule : IHttpModule
{
private HttpApplication _context;
public ErrorHttpModule() {
}
private void ErrorHandler(Object sender, EventArgs e)
{
Exception ex = _context.Server.GetLastError();
//You can also call this to clear the error
//_context.Server.ClearError();
}
#region IHttpModule Members
public void Init(HttpApplication context)
{
_context = context;
_context.Error += new EventHandler(ErrorHandler);
}
public void Dispose()
{
}
#endregion
}
If you're using the traditional asp:FileUpload control, then there isn't a way to check the size of the files before. However, you can use a Flash or Silverlight approach. One option that has been suggested to me is Uploadify
I don't know for sure that this will work, but at least in IIS 7 you might try catching the Error event in an HttpModule that's configured to run for static files. From there, you could redirect to an appropriate error page.
You can catch these in Global (the global.asax.cs file). Add an Application_Error handler - you will get an HttpUnhandledException. Its InnerException will be an HttpException with the message "Maximum request length exceeded".
However, these errors are handled before your page code ever gets loaded or executed, so there is no way for your page to catch the exception or to know it ever happened. After catching this exception, you could stick a message in your Session for later display. You could also call response.Redirect from Global to display a new page, or redisplay the original with the error message from Session.