要实现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页面中切换不同的语言展示。