I have some code in the global.asax file in my application. Each time I debug my website I get a sqlexception for some reason:
void Application_AuthorizeRequest(object sender, EventArgs e)
{
if (Membership.GetUser() != null && Roles.IsUserInRole("UnFilled")) // this is where I get the exception
{
if (Response.Cookies["Expiration"] == null)
{
HttpRequest request = Context.Request;
HttpResponse response = Context.Response;
response.ContentType = ".aspx";
response.Write(request.Url.Host + "/Activate.aspx?account="+Membership.GetUser().Email);
}
}
}
anyone know why I get this, how can I solve it?
I have found an answer, but not sure why it works. It seems to work if I place the coding into a custom http handler.
Thanks to all that contributed.
Related
If Application_Error is triggered by an exception in the application start up i.e. RouteConfigor BundleConfig how can you check if the Request/Response is available? Currently the call to Response.Clear throws System.Web.HttpException with additional information Response is not available in this context.
void Application_Error(object sender, EventArgs e)
{
//Log error
Log.Error(e);
//Clear
Response.Clear();
Server.ClearError();
//Redirect
Response.Redirect("~/Error");
}
Other questions suggest rewriting to not use Response or to use HttpContext.Current.Response or changing IIS config.
In summary; how can I tell if the error has occurred during app start?
You want to check whether it is HttpException.
protected void Application_Error(Object sender, EventArgs e)
{
var exception = Server.GetLastError();
// Log error
LogException(exception);
var httpException = exception as HttpException;
if (httpException != null)
{
Response.Clear();
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
Response.Redirect("~/Error");
}
}
I have been using a compression attribute I found on the web, which is working very well for us.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
the problem I have is that when an exception is thrown, then the screen displays the compressed content (I think!).. it looks like this..
xi��V�4��^ :b���$I"i#!c{��`$c��'wy�N�������H:��38�YS�b?ߕ�!`WSϙ��萧̬n��H����:V(ylZ� �ωԱ��Ϟӱ=�囥�ֺ���V��/>�^R���$٣����T�����J�oRݬz���?6$�<��KՔ��B0�x��V$�����F�h+Ǐ���!���0J��ɒ�h��+VR�p�ۊ�������!��-cccs�Z�%��2{�Ѿ��r�����۩/�,�n��n�f���tܳu�}����.+t��]���̆�����,�c��-�H0)J������dP�� �� ��/�|��#�Z�]O
My question is, is it possible to somehow work around this? Any way I can get this action to work nicely with exceptions?
You can remove the compression filter in Application_Error:
protected void Application_Error(object sender, EventArgs e)
{
(sender as HttpApplication).Response.Filter = null;
}
Alternatively, you can try updating the Content-Encoding response header appropriately but I haven't tried that so not sure if it's going to work.
I added a method called Application_PreRequestHandlerExecute in global.ascx like this:
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
string sExtentionOfThisFile = System.IO.Path.GetExtension(cTheFile);
if (sExtentionOfThisFile.Equals(".aspx", StringComparison.InvariantCultureIgnoreCase))
{
HttpApplication httpApp = (HttpApplication)sender;
string acceptEncoding = httpApp.Request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding))
{
return;
}
acceptEncoding = acceptEncoding.ToLower();
System.IO.Stream requestStream = httpApp.Response.Filter;
if (acceptEncoding.Contains("gzip"))
{
httpApp.Response.Filter = new System.IO.Compression.GZipStream(requestStream,
System.IO.Compression.CompressionMode.Compress);
httpApp.Response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
httpApp.Response.Filter = new System.IO.Compression.DeflateStream(requestStream,
System.IO.Compression.CompressionMode.Compress);
httpApp.Response.AppendHeader("Content-Encoding", "deflate");
}
}
}
It worked when browse normal page.
but if a page contains UPDATE-PANEL error will happen.
I get a PageRequestParserException.
when update-panel async post back, this error happens.
any idea?
I "fixed" by set the EnableEventValidation to false on my page and move compress logic to page's constructor.
Obviously this is not a good solution(close validation).
If anybody know a good solution, pls let me know.
and found that if the project's framework version is 3.5, all works fine,
but if the version is 2.0. this error will happen.
I tried to check if the user is in role at Application_BeginRequest and Application_AuthenticateRequest with this code and it will not work. At BeginRequest the code is never hit and Authenticate it's hit with some of the request and the profiler does not show up.
Checking only for Request.IsLocal works fine.
if(Request.IsAuthenticated)
{
if(User.IsInRole("Admin");
MiniProfiler.Start();
}
Any idea or why it's not working or better way to do it?
[Update] I accepted the awnser but undid it as I didn't quite get it do work
I did the following but the profiler is not showing up at first.
After a few tries it started showing up, even when I tried to acess the site with incognito mode, so no cookie.
protected void Application_PostAuthorizeRequest(Object sender, EventArgs e)
{
if (User.IsInRole("Admin"))
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if (cookie == null)
{
cookie = new HttpCookie("RoleProfiler");
cookie.Value = "yes";
cookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookie);
}
}
}
And I'm checking with
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if ((cookie != null) && (cookie.Value == "yes") )
{
MvcMiniProfiler.MiniProfiler.Start();
}
}
And ending at the end of the request.
protected void Application_EndRequest()
{
MvcMiniProfiler.MiniProfiler.Stop();
}
[Update2] Closing question, ignore this, I was being owned by outputcache.
The cookie feanz mentions is a handy trick, a second method is profiling unconditionally and then abandoning the session for an unauthenticated user:
protected void Application_BeginRequest()
{
MvcMiniProfiler.MiniProfiler.Start();
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if(!CurrentUserIsAllowedToSeeProfiler())
{
MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
}
}
Begin request happens before the user is fully authenticated in the request life cycle.
I solved this issue by adding a cookie if the user is in a role ("Admin" in your case) when the request is authenticated then you can check for this cookie on begin request and initialise the profiler.
It wont't work the first time but should every time after that.
This is my 2cent.
context.AcquireRequestState += (sender, e) =>
{
// Check debug in session. Can be set from Querystring. (?debug=true)
if (HttpContext.Current.Session != null && HttpContext.Current.Session["Debug"] != null)
{
try{
bool debug = (bool)HttpContext.Current.Session["Debug"];
if (debug == true)
MiniProfiler.Start();
else
MiniProfiler.Stop(discardResults: true);
}
catch{
MiniProfiler.Stop(discardResults: true);
}
}// Or always show if Administrator.
else if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
bool admin = HttpContext.Current.User.IsInRole("Administrator");
if (admin == false)
{
MiniProfiler.Stop(discardResults: true);
}
}
else
{
MiniProfiler.Stop(discardResults: true);
}
};
I've implemented Rick Strahl's GZipEncodePage method on my site and it works great for the site itself. However, when my code throws an exception the "Server Error" page looks something like this:
(source: x01.co.uk)
I've tried to hooking into Application_Error in an effort to remove the GZip headers but to no avail. How I can reverse the GZipping on error?
I'm understand that this question is really outdated.
On Application_Error remove Filters from Response, like this
protected void Application_Error(Object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
app.Response.Filter = null;
}
Hope this helps anybody.
In my case I put this in the my basepage class like so:
public class BasePage : System.Web.UI.Page
{
protected override void OnError(EventArgs e)
{
base.OnError(e);
System.Web.HttpContext context = System.Web.HttpContext.Current;
if (context != null && context.Response.Filter != null)
context.Response.Filter = null;
}
}