要實現C# WebAPI Swagger的語言國際化,可以按照以下步驟操作:
Install-Package Swashbuckle.AspNetCore.SwaggerUI
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
services.AddSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.DefaultModelsExpandDepth(-1);
c.EnableFilter();
c.SupportedSubmitMethods(SubmitMethod.Get, SubmitMethod.Head);
c.EnableDeepLinking();
c.DisplayOperationId();
});
}
設置支持多語言的資源文件 創建一個resx文件,用于存儲Swagger UI的文本資源,包括按鈕文本、標簽文本等。在項目中創建一個Resources文件夾,并添加一個SwaggerUI.resx文件。
添加本地化中間件 在Startup.cs文件中,添加本地化中間件。修改Configure方法如下:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var supportedCultures = new[]
{
new CultureInfo("en"),
new CultureInfo("zh"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
app.UseSwagger();
app.UseSwaggerUI();
}
<script>
$(function() {
$('<div id="language-switcher">Language: <select><option value="en">English</option><option value="zh">中文</option></select></div>').insertBefore('.info .title');
$('#language-switcher select').change(function () {
var lang = $(this).val();
$.ajax({
url: '/swagger-resources/configuration/ui',
success: function (data) {
var langUrl = `/swagger-ui/index.html?configUrl=${data.url}&lang=${lang}`;
window.location.href = langUrl;
}
});
});
});
</script>
通過以上步驟,您可以實現C# WebAPI Swagger的語言國際化功能。用戶可以在Swagger UI頁面中切換不同的語言展示。