Azure部署Asp.net Core 2.1魔术登录链接遇双重转义错误
Alright, let's tackle this double escape sequence error you're hitting on Azure—local runs fine, so this is definitely an IIS/Azure-specific configuration issue. Here's how to resolve it step by step:
1. Override IIS Request Filtering via web.config
Azure App Service uses IIS under the hood for ASP.NET Core apps, and its default request filtering blocks double escape sequences. You need to explicitly allow this in your web.config (if you don't have one in your project root, add it alongside Startup.cs):
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <security> <requestFiltering allowDoubleEscaping="true" /> </security> <!-- Keep your existing ASP.NET Core handler/configurations here --> </system.webServer> </configuration>
This tells IIS to allow requests with double-encoded characters, which is common for tokens containing special symbols like / or +.
2. Properly URL-Encode Your Magic Link Token
Another common culprit: if your generated token has special characters, not encoding it before adding to the URL can trigger the double escape error. Update your MagicLinkSender.cs code to safely encode the token:
var token = await _userManager.GenerateUserTokenAsync( user: user, tokenProvider: "MagicLinkTokenProvider", purpose: "magic-link" ); // URL-encode the token to avoid unescaped special characters var encodedToken = Uri.EscapeDataString(token); var magiclink = _urlHelper.Link( routeName: "MagicLinkRoute", values: new { token = encodedToken } );
This ensures the token is passed safely in the URL without triggering IIS's security block.
3. (Optional) Adjust Route Constraints
If your magic link route has strict constraints (like limiting the token to alphanumeric characters), it might reject the encoded token. In your Startup.cs route configuration, modify the route to accept any characters in the token segment:
app.UseMvc(routes => { routes.MapRoute( name: "MagicLinkRoute", template: "login/magic/{token:regex(.*)}", // Allow any characters in token defaults: new { controller = "Account", action = "MagicLogin" } ); });
The :regex(.*) constraint tells ASP.NET Core to accept any value for the token parameter, including encoded characters.
Why This Works Locally but Not on Azure
Local development uses either Kestrel directly or IIS Express, both of which have looser request filtering settings by default. Azure's production IIS environment enforces stricter security rules, hence the error only appears post-deployment.
内容的提问来源于stack exchange,提问作者Ole Kristian Losvik

