ASP.NET 4 WebApi: Backslash Route

I have a WebApi route api/{type}({id})/{prop} and I want to name it with the url as /api/User(domain\username)/groups- key point is "\" in id. I'm sending him out of the client's URL-addresses, for example api/User(domain%5Cusername)/groups. But the route is ignored, and I get 404.

How to pass a slash to a route argument?

+5
source share
1 answer

Like @ATerry suggested in the comments, the problem is not in ASP.NET, but in HTTP.SYS + IIS. Backslashes are replaced by HTTP.SYS with slashes even before going to IIS.
We can work with this using the UrlRewrite IIS module, since it has access to the source (unencoded) URL.

In my example, I came up with the following rule.

<rule name="allow backslash" stopProcessing="true">
    <match url="api/(.*)\((.*)\)(.*)" />
    <action type="Rewrite" url="api/{R:1}({C:1}{C:2}{C:3}){R:3}" logRewrittenUrl="true" />
    <conditions>
        <add input="{UNENCODED_URL}" pattern="\((.*)(%5C)(.*)\)" />
    </conditions>
</rule>

This is not ideal, as it is very specific. It would be more helpful to have a general rule that simply handles %5C.

The idea is to catch the URL with %5Cand rewrite it to return it. This is a little strange, but it works.

In addition to the rule, we need to install allowDoubleEscaping=falsein system.webServer/ security/ requestFiltering:

    <security>
        <requestFiltering allowDoubleEscaping="true">
        </requestFiltering>
    </security>

, Mvc/Api, (%). :

public virtual DomainResult GetObjectProp(string type, string id, string prop)
{
        id = Uri.UnescapeDataString(id);
}
+5

Source: https://habr.com/ru/post/1672857/


All Articles