Why can't I find or use UrlEncode in Visual Studio 2010?
I have a string that I'd like to encode into the standard URL format. From what I've found, I should be able to do this via the httpUtility.urlEncode
method, but I don't seem to have that available.
I've added "using" references to both System.Web
and System.Net
to no avail. I've also seen other references to server.urlEncode amongst other variants, but I don't see the method anywhere.
I'm using the latest version of C# in Visual Studio 2010. Is the method开发者_运维问答 called something different in this version, hidden somewhere else, or am I completely off base?
By default, new projects in Visual Studio 2010 target the .NET Framework 4.0 Client Profile, which does not include the System.Web
assembly.
You can change the version of the Framework that your project targets in your project's Properties. Under the "Application" tab, select ".NET Framework 4.0" from the combobox labeled "Target framework".
Then, make sure that you have added a reference to System.Web
using the "Add Reference" dialog.
Finally, add a using
directive to the top of your class for the System.Web
namespace:
using System.Web;
You'll find the various overloads of the UrlEncode
method in the HttpUtility
class. Sample code:
HttpUtility.UrlEncode("http://www.google.com/");
In .Net 4.5 you can (should?, 'please use' says a Katana comment) use the System.Net.WebUtility.UrlEncode method.
It can't be named differently since Visual Studio doesn't supply the class or method names, the .NET framework does.
All I can tell you is that the System.Web.HttpUtility AND System.Web.HttpServerUtility classes contain a method called UrlEncode(string)
.
If your project target ".NET Framework X Client Profile",you cannot not use "System.Web",but you can use "Uri.EscapeUriString | Uri.UnEscapeUriString" instead.
Yes, adding the reference was my answer. But be sure you double check the project, that it is in, if you have more than 1 project in your solution. I had a solution with 3 projects. System.Web
was added to 2 projects but not the 3rd project.
I spent an hour trying to figure out why I couldn't use HttpUtility
since it was a Reference in the main project. But I didn't check the sub-projects of the Solution.
Hope it helps someone.
Because you only see AspNetHostingPermission
, AspNetHostingPermissionAttribute
, and AspNetHostingPermissionLevel
, I strongly suspect (like the other guys) that you're missing a reference.
The best you can do is start a new project, because it's pretty complicated to add/remove references without ruining your entire project.
How to: Add or Remove References in Visual Studio (MSDN) shows how to add/remove references. In your case, you should check/add the System.Web
reference.
精彩评论