简体   繁体   中英

Best way to validate QueryString parameters in c#

I receive numeric variables in my queryString.

I'm doing validation with the following code:

if (!String.IsNullOrEmpty(Request.QueryString["num"]))
    if (!int.TryParse(Request.QueryString["num"],out value)
        throw SecurityError;

Is that validation safe enough? Is it the most efficient? (Let's assume that every int number I get is valid)

The only case you are not handling in the above code is when no 'num' is passed in the query string. I'm not sure what you want to do in this case, but you could remove the outer if block, so that your exception is thrown if the parameter is not passed at all.

if (!int.TryParse(Request.QueryString["num"],out value)
    throw SecurityError;

Also, 'SecurityError' would seem a strange type of exception to throw in the case of a non-numeric argument.

Otherwise it looks fine.

It is safe and efficient. You could even remove the first if :

if (!int.TryParse(Request.QueryString["num"], out value)
    throw SecurityError;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM