Displaying expected errors to users in ASP.NET - c#

I have found huge amounts of information (ie, this) on how to handle unexpected errors in ASP.NET, using the Page_Error and Application_Error methods as well as the customErrors directive in Web.config.
However, my question is what is the best way to handle EXPECTED errors. For example, I have a page to display a record. Each record has a specific list of users who are allowed to see it. Since many users may have the "View Records" role that are not on said list, I have to write some code on the page to filter them.
protected void Page_Load(object sender, EventArgs e)
{
var user = Membership.GetUser();
if (!CanUserViewThisRecord(Request["id"], user.Username)
{
// Display an error to the user that says,
// "You are not allowed to view this message", and quit.
}
else
{
// Display the page.
}
}
What are the best practices for handling this kind of error? I can think of a few possibilities:
Redirect to an error page.
Put a label on every page called "lblErrorText". Leave it blank unless there is an error.
Raise an exception and let the standard error handling deal with it.
This feels like a basic question and for that I apologize, but just about everything I've found has been in reference to unexpected exceptions. It's not that any of the above possibilities are hard to implement, but I'd like to use a standard, recommended method if possible.
NOTE: Thanks everyone for the answers. I want to clarify that users would NOT have the ability to click links to records they're allowed allowed to view. This question is more in the interest of being defensive. For example, since the record ID is in the URL someone could potentially enter the ID of a forbidden record in the address bar. Or User A who is allowed might e-mail a link to User B who is not. It seems I may not be using the words "exception" and "error" in the correct way, but hopefully the scenario makes sense.

In the interest of failing gracefully, I'd go with the option to display a message on the page.
Even better is error prevention; if you know ahead of time that the user won't be able to do anything on the page, don't provide a link to it. Generally, users should only see the things that they are allowed to do.

As others have mentioned, I would prefer to prevent this before it gets sent, either by disabling the functionality for these users, or catching it with javascript before the page is sent.
you would still need to check on the server that the user is allowed to make use of a control, and in such cases the suggested label would be preferable as a solution to the other 3 given.
A further solution however would be to provide a hidden value to the page which is checked by javascript within the page, generating either an alert or a more easily spotted error dialogue than a label somewhere which might be missed leading to confusion as to why nothing happened.
Edit based on questioner's comments: if modifying a number in a URL is all that is required to point to records the user is unauthorized to use, would POST perhaps be a better method to use than GET? that way the way this error is handled is less important, as no standard user would encounter it.

Of your three options, the third would be my least favored. It's not really an exception for a user to try to view a record you told him was there. Redirecting to an error page is more reasonable, as is the error label. However, neither is particularly user-friendly.
I don't know how your UI is structured, but it seems to me that you shouldn't let the user try to view a record if you know that the user isn't allowed to view it. That is, if you know that the user can't view that record, then don't give him the opportunity to click on it. Never get to the point where you have to say, "You can't view this record."
If you can't prevent the user from trying to view the record, I think a pop-up message box would be preferable to either of your first two options.

in my opinion this question is more methodology then tech..
i think is more right to show the error message near the object/action that cause the error.
if you send him to another page he will lost is orientation and it not be clear what cause this error.
so in my opinion is more right to put the error message in the same page.
and maybe give him the opportunity to correct..

Related

ASP.NET MVC - If an error happens and the view is returned, uploaded file is not returned

I created a form that gives the user an option to upload a PDF file using an input with a file type. If an error occurs and the view is returned, the file is no longer there. I've been researching for hours, and everyone is saying that it would be a security risk or whatever if that functionality was available, but surely there is something that can be done so the user doesn't have to resubmit the file? The user may not notice that their file is no longer there and it just doesn't seem like good UX to make the user do that. Any thoughts? I'd appreciate any feedback on either a fix or a different way to handle this scenario.

Lost in validation design

I need some ideas... I have a SQL table that contains error codes, and messages that I will use to display in the web application based on the code column for validation purposes.
If by using server side to do checking, I can load the messages whenever they hit the condition by matching with the error code I put, and display at the menu. But each time a post back needs to be done to show the error code and message, by using the update panel, I can do a partial postback, still I can't style as I want.
If I using client script to check. i can style as I want, but I will need to load the error code and message on each pageload, and chop it 1 by 1, javascript to process and based on code, show the error message, I dont think it is a good idea, is there any better idea to achieve this? I kinda stuck due to my limited knowledge, any idea will be great, thanks

Set File for upload on a type="file" html element

I've been researching this for a couple of days now and have made no headway regarding a possible way of doing this.
Programmatically I've been able to invoke the "Choose File to Upload" dialog but whenever it inputs the File and Path and try to submit it it will not accept the input value.
WebBrowser.Document.GetElementById("field-file").InvokeMember("click")
Allows the .click() method to fire.
Whenever I submit it, it gives me an error that the field must be filled.
Is there another Event that I need to invoke before submitting it?
As I understand the value properties of this input type is disabled for security reasons - but surely it's just a matter finding a workaround?
As you say "for security reasons". So, there should not be a workaround. Otherwise it would be a security flaw, that is not intended and will surely be fixed.
On the other hand, W3C defines the following:
User agents may use the value of the value attribute as the initial
file name.
But I do not know any current browser that supports this.

IE shows a previously cached version of my page

my scenario is this; the user selects the list of reports they wish to print, once they select and click on the a button, i open up another page with the selected reports ready for printing. I am using a session variable to pass reports from one page to another.
first time you try it, it works fine, second time you try it, it opens the report window with the previous selected reports. I have to refresh the page to make sure it loads the latest selections.
is there a way to get the latest value from the session every time you use it? or is there a better way to solve this problem. open for suggestions...
Thanks
C# Asp.net, IE&7 /IE 8
After doing some more checking maybe if you check out COMET it might help.
The idea is that you can have code in your second page which will keep checking the server for updated values every few seconds and if it finds updated values it will refresh itself.
There are 2 very good links explaining the imlementation.
Scalable COMET Combined with ASP.NET
Scalable COMET Combined with ASP.NET - Part 2
The first link explains what COMET is and how it ties in with ASP.NET, the second link has an example using a chat room. However, I'm sure the code querying for updates will be pretty generic and can be applied to your scenario.
I have never implemented COMET yet so I'm not sure how complex it is or if it is easy to implement into your solution.
Maybe someone developing the SO application is able to resolve this issue for you. SO uses some real-time feature for the notifications on a page, i.e: You are in the middle of writing an answer and a message pops up in your client letting you know someone else has added an answer and to click "here" to refresh.
The proper fix is to set the caching directives on the HTTP response correctly, so that the cached response is not reused without validation from the server.
When you fail to specify the cache lifetime, the client has to "guess" how long the response is good for, and the browser's guess probably isn't what you want. See http://blogs.msdn.com/b/ie/archive/2010/07/14/caching-improvements-in-internet-explorer-9.aspx
It's better to use URL paramaters. So you have a view of value of the paramaters.

Preventing anonymous user from submiting form many times in ASP.NET without SqlMembershipProvider

I have a simple form that dumps selected answers to XML file. How to prevent anonymous user from submitting this form many times?
I am not looking for totally bulletproof solution, and I have a limitation that I cannot use the database, and therefore no SqlMembershipProvider.
Will some cookie checking work? How to do this right?
Thank you in advance.
Update: To be more precise, I do not only mean some accidental submitting of the form but to prevent user that visited the site a week ago from submitting this form again.
In short, you can't totally reliably. If you're not bothered about something bullet proof as you say you could either
a) Persist a cookie to the client machine and check for it next time someone posts. Obviously the user can delete cookies so not brilliant.
b) You could store the IP address of where it was submitted from. Problem with this is that you'll prevent multiple users behind the same IP submitting i.e. proxy, and the same user could post from different locations.
Neither is particularly good and if it's possible I'd recommend asking them to input an email address at the start, store the post as non-confirmed, email a confirmation link out and only make the post official if they click on it. Again, not bullet proof as it doesn't stop people posting with multiple email accounts but it's a little better than the options above.
HTH
Use the session variables to keep track of what your user is doing.

Categories

Resources