How to get Error code on custom error page - c#

I have a common custom error page for my asp.net website because it's common it is shown on every error I want to found the last error code which was occurred and redirected to my that custom error page so that I can show right message according to the error which was occurred.
Note : solution have to be session based, I don't want any user to show error which was occurred on any other user's system of course.

Do you use IIS or Apache?
For Apache
Configuring Apache to serve customized error pages is extremely easy; there is a section of the httpd.conf file devoted to this. It takes just one directive per error to achieve. If you open the conf file and scroll right down to almost the very bottom of section two, you’ll see the section you need to edit.
By default, these directives are commented out, but all you need to do is un-comment each directive and then change the path to point to your own error page.
ErrorDocument 404 /errordocs/404error.html
For IIS
IIS 6: Edit Website or virtual Directory then Userdefinded Error.
There you can edit all error files and change to a user defined asp.net file.
IIS 7:
Detailed Error Message see:
http://blogs.msdn.com/b/rakkimk/archive/2007/05/25/iis7-how-to-enable-the-detailed-error-messages-for-the-website-while-browsed-from-for-the-client-browsers.aspx

Not good idea what you try to do. You must capture the errors on the code that they occur inside the page, and show the message on that page - stay on page - and if this is possible give the user the opportunity to correct it. If your error gets out of your try/catch and out of control then log it and fix it.
The only error that you can show to your user is the "non found page".
You can get the last error as Exception LastOneError = Server.GetLastError();
And there you can read more about errors: How do I make a "generic error" page in my ASP.NET application so that it handles errors triggered when serving that page itself?
and How to tell if an error captured by my global.asax was displayed on the screen of the user

What I would suggest is extending the UI.Page class and using that class for all your pages.
In that class (I know vb not c# but same principle and easy to convert) use the following code:
Public Class _PageBase
Inherits System.Web.UI.Page
#Region "Page Functions"
Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error
Session("error_StackTrace") = Server.GetLastError.StackTrace.ToString
Session("error_Message") = Server.GetLastError.Message.ToString
Session("error_Page") = Request.Url.ToString
Session("error_Source") = Server.GetLastError.Source.ToString
Server.ClearError()
Response.Redirect("~/errors/Error.aspx")
End Sub
#End Region
End Class
This will fire on all pages using that base class, and pass the last 'server' error (which will be the error the user caused), store all the details in session and pass it over to your error page. Then you can do as you wish.

Related

MVC Redirect to another page

I have a controller which processes an uploaded file.
In that controller, I return the user to a SharePoint list depending on the successful parsing of that file. I am able to enter a direct URL, but I am opening this page in a form so I need to change the window.top.location instead of just window.location. I tried doing this a few ways such as returning a JavaScript result, but I received some browser warning messages I'd like to avoid.
I ended up making a partial razor view which grabs a parameter from the query string in order to determine which list it should go to. The function works fine, but the page is seemingly inactive when I return it using:
return Redirect("~/Parsing/ParsingRedirector?List=MasterDealer");
My page exists in the folder, but I get an error stating "The resource cannot be found. "
Any reason why that's happening? I admittedly don't have a full understanding of MVC or even close to it at this point.
Try this:
return RedirectToAction("ParsingRedirector", "Parsing", new { List = "MasterDealer"});
This may be of help:
http://www.dotnet-tricks.com/Tutorial/mvc/4XDc110313-return-View()-vs-return-RedirectToAction()-vs-return-Redirect()-vs-return-RedirectToRoute().html
Keep in mind that, per that article, in the case of Redirect "you have to specify the full URL to redirect."

Modifying AccessDenied.aspx

I'm working on a website I didn't build. As far as I understand, AccessDenied.aspx comes with some default behaviour, such as the default error message for a failed login attempt is ''Your login attempt was not successful. Please try again.'
I want to change the message conditionally so it shows a different message if they have exhausted their login attempts.
I have some code in AccessDenied.aspx: <asp:Literal ID="msgFailedLogin" runat="server" EnableViewState="False"></asp:Literal>
When I try to access the fields from AccessDenied.aspx.cs using
msgFailedLogin.InnerText = "New text";
the compiler tells me
msgFailedLogin does not exist in current context.
I am able to access it using
((Literal)Login1.FindControl("msgFailedLogin")).Text = "New text";
Is there some built in behaviour interfering with my attempt to access this field using the typical convention of <id>.<method/property>?
I would include more code but none of it seems to be relevant.

ASP.NET invalid script resource request instead of redirect

Several bots/crawlers are scanning our websites, and I'm wondering if there is something I can change that when a page cannot be found (for example: www.mysite.com/scriptresource.axd)
it will be redirected to a page instead of displaying the error:
Message:
This is an invalid script resource request.
I've configured the global.asax that I will receive mail on errors, but I'm receiving tons of those emails that a bot has been trying to access a non-existing page. e.g. ScriptResource.axd
Please take note of the following:
You need to login before you can do anything on the website, but the bot will cause this error somehow.
If you're logged in and try to reach a non existing page you end up
with a manual 404 (RemoteOnly) error.
In the Global.asax I've added a check on Session_start for IP's that they will be redirected to Google. However, they can still cause this error.
What do I miss?
If I understand you perfectly, you can do such as below:
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim ctx As HttpContext = HttpContext.Current
Dim file_ext As String = ctx.Request.CurrentExecutionFilePathExtension
If file_ext = ".axd" Then
ctx.Response.Redirect("http://bing.com")
Else
' email error detail
End If
End Sub

Accessing https page

I am currently adding an aspx page to my web site (.net) where my clients can insert credit card details.
I would like to give access for that page from several pages only (lets call them a.aspx and b.aspx) and if someone tries to access this page from c.aspx he won't be able to do so.
Is there a way to limit the redirect to a page for few pages only?
I've tried to check at the page event what is the source of the call, with the "sender" object, however I am not sure it the right way to go.
Hope the question is clear enough.
What you need to know to do this is the referer.
The referer is, briefly, the page that brought you to the page you are currently at.
I believe this should get the referrer for ASP.net
Request.Server["HTTP_REFERER"]
Then you can just check and see if the referer matches your desired origins. However, I'm not sure about the ease/prevalence of referer spoofing, or if it even exists.
Yes there is - have a look at the HttpWebRequest.Referer property.
Using this you can see from which page the request to c.aspx is made - if it's not a.aspx or b.aspx you can redirect the user away.
As menitoned previously you need to check the current UrlReferrer, here is an example in vb.net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim bRedirect As Boolean = True
Try
If Not IsNothing(Page.Request.UrlReferrer) Then
Dim sReferer As String = Page.Request.UrlReferrer.ToString()
If sReferer.Contains("/a.aspx") Or sReferer.Contains("/b.aspx") Then
bRedirect = False
End If
Catch ex As Exception
' Raise exception, decide whether or not to redirect
End Try
If bRedirect Then
Response.Redirect("~/x.aspx", True)
End If
End Sub

Unhandled Exception CachedRawResponse asp.net

Unable to cast object of type 'System.Web.Caching.CachedRawResponse' to type 'System.Web.Caching.CachedVary'.
I'm getting this on an AJAX call to an aspx page, and can find no information about it in webland. CachedRawResponse isn't even on MSDN. Does anyone know anything about it, or maybe point me in the right direction?
We recently had the same problem, and it turned out (in our case) that the page output cache module is rather sensitive to how you set your Response.Cache.VaryByXyz properties. We used code like the following in our HTTP compression module:
if (IsBrowserSupported(userAgent))
{
Response.Cache.VaryByHeaders["Accept-Encoding"] = true;
...
}
Unfortunately, this causes ASP.NET to throw a fit when the page is cached after a call by a non-supported browser, and subsequently requested from the cache by a supported browser.
Not setting any VaryByXyz causes a CachedRawResponse to be stored in the ASP.NET output cache, but if you do set any VaryByXyz during your request, ASP.NET expects a CachedVary at that location. And instead of checking whether the cached page is of the right type, the framework just casts, resulting in an InvalidCastException.
Moral of the story: always set the VaryByXyz consistently, regardless of the request headers or other non-request-related variables. In our case, placing the VaryByHeaders outside of the if solved the error.

Categories