我们有一个 Webapi,它应该能够根据传递的用户获取数据。此用户包含域,因此参数类似于 Domain\Username
。
最后我们的 API 调用应该是这样的:
http://servername/api/controller/ 域\用户名
或编码
http://servername/api/controller/ 域%5C用户名
两个 URL 都返回 Not Found 并且 Controller 没有被触发(断点没有命中)
我找到了这个,它说你不能将 %-Values 直接传递给 URL。 Pass in Active Directory user name (DOMAIN\etc) in asp.net MVC URL还有这个How to URL encode parameters in ASP .NET MVC . 但是,当我传递 %5C 以外的其他内容时(例如,%20 用于空格或 %25 用于 % 或 %92 用于撇号)它正在工作(断点命中和正确结果)。
我知道我可以使用 ?parameter=EncodedUsername
,这是有效的,但用户名只是一种可能性,所以如果没有必要,我不想使用这种方式,因为我不需要在每种情况下都有反斜杠。
我的路线是这样的:
[HttpGet("{firstParameter}/{usernameWithDomainAndBackslash}")]
最佳答案
尝试对反斜杠使用 DoubleEscaping。
修改您的 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>
对于/,它将被编码为 '%252F' (%2F -> %252F)
将请求发送到服务器端,在那里解码。
关于路由中的 C# WebAPI 核心反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38218180/