.NET Core 3.1 + Swashbuckle.AspNetCore 5.6.3:实现SwaggerUI自动Base64编码User-Identity请求头
Absolutely! You can absolutely improve the user experience by letting folks just type their email directly in Swagger UI, with the Base64 encoding happening automatically before the request is sent. Here's how to do it:
Step 1: Update the Operation Filter's Description
First, tweak your RequireUserIdentityOperationFilter to clarify that users can input an email directly (no manual encoding required), and update the example to reflect this friendlier input:
public class RequireUserIdentityOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { var hasRequireUserIdentityFilterAttribute = context.MethodInfo .GetCustomAttributes(true) .OfType<RequireUserIdentityFilterAttribute>() .Any(); if (hasRequireUserIdentityFilterAttribute) { operation.Parameters.Add(new OpenApiParameter { Description = "User email (will be automatically Base64 encoded as {\"email\": \"your-email\"}). Example: test@test.com => ewogICJFbWFpbCI6ICJ0ZXN0QHRlc3QuY29tIgp9", Name = "User-Identity", In = ParameterLocation.Header, Schema = new OpenApiSchema { Type = "string", Example = new OpenApiString("test@test.com") // Show email as the intuitive example } }); } } }
Step 2: Add Custom JavaScript to Swagger UI
We’ll inject a small script into Swagger UI that intercepts outgoing requests, checks if the User-Identity header contains an email, and auto-converts it to the required Base64-encoded JSON format.
For .NET Core 3.1 (Startup.cs):
- Create a custom JS file: Add
wwwroot/swagger-ui/custom.jswith this code:
// Override the default fetch function to intercept requests const originalFetch = window.fetch; window.fetch = function(url, options) { // Check if the User-Identity header exists in the request if (options?.headers?.has('User-Identity')) { const inputValue = options.headers.get('User-Identity'); // Simple email validation regex (adjust for stricter checks if needed) const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (emailPattern.test(inputValue)) { // Build the required JSON object, stringify it, then Base64 encode const userJson = JSON.stringify({ email: inputValue }); const base64Encoded = btoa(unescape(encodeURIComponent(userJson))); // Update the header with the encoded value before sending options.headers.set('User-Identity', base64Encoded); } } // Pass the modified request to the original fetch function return originalFetch.apply(this, arguments); };
- Configure Swagger UI to load the script: In your
Startup.Configuremethod, update the Swagger UI setup to inject the custom script:
app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API V1"); // Inject the custom encoding script c.InjectJavascript("/swagger-ui/custom.js"); });
How It Works
When a user types an email like test@test.com into the User-Identity header field in Swagger UI and clicks "Execute":
- The script catches the outgoing request before it’s sent
- It validates that the input matches an email format
- Converts the email into the required JSON object:
{"email": "test@test.com"} - Encodes that JSON string to Base64
- Replaces the header value with the encoded string before forwarding the request to your server
This keeps your existing server-side validation intact (it still receives the expected Base64 encoded value) but eliminates the need for users to handle manual encoding.
内容的提问来源于stack exchange,提问作者Aleks Vujic

