Andornot Consulting Inc.
Home Page
Home Page
 |  | 

Friday, October 20, 2006

The Uri gotcha that gotcha'd me good

When working on ASP.NET web applications, it's not unusual to be working with the System.Uri class, which is an object representing a uniform resource identifier (URI). It can spit back handy references to various properties of a URL, such as host, query, scheme, yada yada.

I was down in the dingy Andornot lab today, working on the Onesearch class library and feeling clever because I was using Uri objects to hold WebPublisher search URLs instead of mere strings. But strangely, something kept going wrong whenever I called upon the Uri to actually perform a web request. The search text I was passing in was not getting encoded. (This is so "doctor & nurse" gets encoded to "doctor+%26+nurse" and doesn't make WebPublisher cry like a wet-nappied baby.)

I encoded that string every which way I knew how, and viewed the results in the trace log. It was going in encoded, but somehow whenever I asked for the whole Uri as a string to make a web request, it came out "doctor+&+nurse". I was going completely bananas. Had I slipped into some alternate Twilight Zone universe? Was there a bug in the .NET 2.0 framework? Where was my encoding? Double U Tee Eff!

I finally figured it out. I had been asking for Uri.ToString(), which indeed returns a full string representation of the Uri, sans encoding, even if you had forced encoding upon any portion of the Uri previously. Buggrit! Millenium hand and shrimp! I humbly accept my chastisement from the gods, and ask instead for Uri.AbsoluteUri(), which returns a full string with encoding. Amen.

As a postscript, UriBuilder.Query is a trip-up as well. Do not append a string directly to this property! I did, and now I'm sorry.

Don't

uriBuilder.Query += "&QI0=smith";

What does that get you? Two question marks preceding the query instead of one.

Do

uriBuilder.Query = uriBuilder.Query.Substring(1) + "&QI0=smith";

0 Comments:

Post a Comment

<< Home