How to handle this error gracefully in asp.net?

I have an asp.net site .... I would like to know how to handle this error gracefully when a user enters and sends an illegal character (xss attack).

"a potentially dangerous Request.Form value was detected at the client (ctl00 $ TextBox1 =" ") ......... etc.

I can turn off the requestvalidation attribute and write code to filter the string with illegal characters, but I think it is not a good practice to turn it off. I would prefer to leave this and catch the error, elegantly say, redirect the user to another page that will notify him of the error. How would you do that?

+3
source share
4 answers

, , . , - .

:

  • ,
  • ( )

, :

public class UserInputValidator : BaseValidator
{

    private HttpRequest Request
    {
        get { return HttpContext.Current.Request; }
    }


    protected override bool ControlPropertiesValid()
    {
        //Override the base functionality because this will check for a control to validate, what we won't do. 
        return true;
    }

    protected override bool EvaluateIsValid()
    {
        bool isValid = true;
        var message = new StringWriter();
        if (Request != null)
        {
            //Validate input will enable request validation. 
            Request.ValidateInput();
            NameValueCollection formValues = Request.Form;
            foreach (string formKey in formValues.Keys)
            {
                try
                {
#pragma warning disable 168
                    //Access the form variable to trigger request validation.
                    string formValue = formValues[formKey];
#pragma warning restore 168
                }
                catch (HttpRequestValidationException)
                {
                    string orgValue = Request.Unvalidated.Form[formKey];



                    message.WriteLine("The following input is not allowed: {0}", HttpUtility.HtmlEncode(orgValue));
                    isValid = false;
                }
            }
        }
        ErrorMessage = message.ToString();
        return isValid;
    }
}

, , ValidateInput . , .

, , - ( , asp.net 4.5), .

+2

, - , .

, - Application_Error global.asax, .

+1

, , , , , ... (, , ).

You can then redirect to the error message page. Alternatively, if you leave it as the already mentioned Application_Error descriptor (or perhaps the OnError method on the page), you can redirect them to the page with the error message, basically doing the same thing.

0
source

Check with JavaScript first and display the error message immediately. And repeat this check in the Application_Error event, as Mitchell said.

0
source

Source: https://habr.com/ru/post/1735313/


All Articles