Darren
Darren

Reputation: 67

Trim exception message

I'm trying to trim an exception message with the below code:

Response.Redirect("IllegalCharactersError.aspx?error=");
string message = ex.Message;
string cleanMessage = message.Substring(message.IndexOf("=") + 1);
Session.Add("IllegalCharactersError", cleanMessage.Replace("\\", ""));

Here is a sample of the string: A potentially dangerous Request.Form value was detected from the client

(ctl00$Main$EmployerRegistrationCtrl$CompanyDetails$CompanyTradingAs="'<'My Company Trading").

I only want to display '<'My Company Trading but my label is displaying \"'<'My Company Trading\"). with back slashes so its not displaying and I cant seem to remove, any ideads how to acheive this?

Thanks Darren

Upvotes: 0

Views: 608

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460238

You should use HttpUtility.HtmlEncode:

lbl.Text = HttpUtility.HtmlEncode(value);

Use HttpUtility.HtmlDecode to read the Text of the label later:

string value = HttpUtility.HtmlDecode(lbl.Text);

If you want to transfer the error-message via URL, you need HttpUtility.UrlEncode and later HttpUtility.UrlDecode.

But i'm not sure where you are getting the backslashes from. The original error-message has none, are you masking it somewhere?

For the sake of completeness, here you find informations how you prevent the "dangerous Request.Form value"-error: A potentially dangerous Request.Form value was detected from the client

Upvotes: 2

Roland Illig
Roland Illig

Reputation: 41686

Did you make the IllegalCharactersException (or however it is called in your example) yourself? If you did, you should add some useful properties to it:

ex.OffendingValue
ex.Field

These properties should be filles when the exception is thrown.

That saves you from parsing the string at all.

Upvotes: 1

Related Questions