在WCF Web服务中是否需要调用URLDecode处理参数?
HttpUtility.UrlDecode for WCF PUT method parameters from UriTemplate? I've written a WCF web service in C# with the following PUT operation contract:
[OperationContract] [WebInvoke(Method = "PUT", UriTemplate = "MobileDevice?name={name}&make={make}&model={model}&serial={serial}&software={software}")] MobileDeviceView RegisterMobileDevice(string name, string make, string model, string serial, string software);
In my implementation, I'm currently manually decoding each parameter like this:
public MobileDeviceView RegisterMobileDevice(string name, string make, string model, string serial, string software) { string safeName = HttpUtility.UrlDecode(name); string safeMake = HttpUtility.UrlDecode(make); string safeModel = HttpUtility.UrlDecode(model); string safeSerial = HttpUtility.UrlDecode(serial); string safeSoftware = HttpUtility.UrlDecode(software); // ... rest of the implementation }
Is this manual decoding actually necessary?
Great question! The short answer is no—you don't need to manually call HttpUtility.UrlDecode on these parameters.
Here's why: When using WCF's WebHttpBinding (required for REST-style services with WebInvoke), the framework automatically handles URL decoding of parameters specified in the UriTemplate. By the time the parameters reach your service method, they've already been converted to their original plain-text values.
Manually calling UrlDecode here can even cause unintended issues. For example, if a client sends a parameter like Jane%2BDoe (where %2B encodes a +), WCF will decode it to Jane+Doe automatically. Running that through HttpUtility.UrlDecode a second time will turn the + into a space, resulting in Jane Doe—which isn't the value the client intended to send.
You can simplify your implementation to use the parameters directly:
public MobileDeviceView RegisterMobileDevice(string name, string make, string model, string serial, string software) { // Parameters are already decoded—use them directly // ... rest of the implementation }
A quick caveat: This automatic decoding only applies to parameters pulled from the URI via UriTemplate. If you were manually reading raw request data (like from the request body or query string without using template parameters), you might need to handle decoding yourself—but that's not the case here.
内容的提问来源于stack exchange,提问作者Goldorak84

