nicn
nicn

Reputation: 93

C# WebAPI Core Backslash in Route

We have a Webapi that should be able to get data based on the passed user. this user includes a domain, so the parameter is something like Domain\Username.

In the end our API-Call should look like this: http://servername/api/controller/Domain\Username or encoded http://servername/api/controller/Domain%5CUsername

Both URLs return Not Found and the controller is not fired (breakpoint does not hit)

I have found this, which says that you cannot pass %-Values to URL directly. Pass in Active Directory user name (DOMAIN\etc) in asp.net MVC URL and this How to URL encode parameters in ASP .NET MVC. However, when I pass something else than %5C (e.g. %20 for space or %25 for % or %92 for apostrophe) it is working (breakpoint hit and correct result).

I know that I could use ?parameter=EncodedUsername, which is working, but username is only one possibility, so I don't want to use this way if it's not necessary as I do not have backslashes in every case.

My Route looks like this: [HttpGet("{firstParameter}/{usernameWithDomainAndBackslash}")]

Upvotes: 3

Views: 2037

Answers (1)

Ted Zhang
Ted Zhang

Reputation: 371

Try use DoubleEscaping for backslash.

  1. Modify your web.config:

    <configuration>
      <!--
        Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
      -->
      <system.web>
        <httpRuntime requestPathInvalidCharacters=""/>
      </system.web>
    
      <system.webServer>
        <security>
          <requestFiltering allowDoubleEscaping="true"></requestFiltering>
        </security>
        <handlers>
          <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
        </handlers>
        <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
      </system.webServer>
    </configuration>
    
  2. For /, it will be encoded to '%252F' (%2F -> %252F)

  3. Send the request to Server side, the decode it there.

Upvotes: 1

Related Questions