I have a REST WCF service that has a method that gets a parameter as a string. This string can contain slash / character. It makes my request wrong, as I think the URL goes
While the accepted answer will work in some cases, where the URI parameter is at the end of the URI, it will not work if a URI parameter is in the middle of a URI. But with just a few configuration settings, you can allow your application to accept encoded forward slashes.
The HttpListener
that takes incoming requests uses an internal HttpListenerRequestUriBuilder
to parse the raw request URI.
The HttpListenerRequestUriBuilder
will or will not unescape the encoding based on a setting. Add the following setting to your app.config
file:
<configuration>
<system.net>
<settings>
<httpListener unescapeRequestUrl="false"/>
</settings>
</system.net>
</configuration>
This will allow the incoming Message
's To
headers to be correctly built without unescaping the URIs.
If you are using a version of .NET before 4.5, I believe you may also need to add another setting instructing the System.Uri
class to not escape slashes for http
and https
paths. This setting is as follows:
<configuration>
<uri>
<schemeSettings>
<add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes"/>
<add name="https" genericUriParserOptions="DontUnescapePathDotsAndSlashes"/>
</schemeSettings>
</uri>
</configuration>
Uri.Match
and the default QueryStringConverter
should still work with the unescaped text, so a method like:
[WebGet(UriTemplate = "foos/{bar}/baz"]
public Baz GetFooBaz(string bar)
{
// ...
}
will provide an unescaped string to the bar
parameter.
Try forcing a \ before each /. (normally it forces the metacharacters to be read as a normal character)
I solved it.
URI template is the key.
If I define URI this way, it produces the exception above:
[OperationContract()]
[WebGet(UriTemplate = "/testmethod/{testvalue}"/*, BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml*/)]
string TestMethod(string testvalue);
By modifying this way, it works:
[OperationContract()]
[WebGet(UriTemplate = "/testmethod?v={testvalue}"/*, BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml*/)]
string TestMethod(string testvalue);
Anyway, Uri.EscapeDataString is needed!