When can HttpUtility.HtmlEncode() reduce risk of XSS attack?

When can HttpUtility.HtmlEncode() reduce risk of XSS attack?

I was under the impression that it was best practice to encode the URL before I call Redirect().

For example:
                    return Redirect(HttpUtility.HtmlEncode(returnUrl));

But then was told it makes no difference, since encoding it just means the browser needs to decode it. And, all that matters is how you protect yourself from incoming malicious URL's. Obviously, a hacker can reformat any outputted URL.

Where and when does it make sense to use HttpUtility.HtmlEncode(returnUrl) ?

newbiewebSr. Software EngineerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Shaun VermaakTechnical Specialist IVCommented:
Are you not confusing HttpUtility.HtmlEncode and HttpUtility.URLEncode?

HttpUtility.HtmlEncode would prevent XSS when attacker saves malicious HTML/JS etc. content in a form and you display is later in a process
You should HttpUtility.HtmlEncode(returnUrl) anytime you need to display it on the page, for example in the exceptions/errors page. However, if the returnUrl is generated on the server side or is validated such that

1- its a proper URL
2- Its relative URL or to a trusted domain

then you may skip the encoding. Again, it is unlikely that you'd need to display the return URL.

HtmlEncode is unnecessary when doing a Redirect. You may need URLEncode if you are appending query params to the returnUrl, for example.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
newbiewebSr. Software EngineerAuthor Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.