你可以在你的应用程序中为多种不同的语言生成多个swagger文档.下面是一个简单的例子:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1-en", new OpenApiInfo { Title = "API (English)", Version = "v1" });
c.SwaggerDoc("v1-fr", new OpenApiInfo { Title = "API (French)", Version = "v1" });
c.SwaggerDoc("v1-es", new OpenApiInfo { Title = "API (Spanish)", Version = "v1" });
});
您可以做的另一件事可能是定制Swagger用户界面以允许语言 Select .下面是一个基本的例子,说明如何做到这一点:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1-en/swagger.json", "English");
c.SwaggerEndpoint("/swagger/v1-fr/swagger.json", "French");
c.SwaggerEndpoint("/swagger/v1-es/swagger.json", "Spanish");
});
有关更多信息,请参阅Swagger Github Documentation,还有其他选项,如翻译文本、使用浏览器语言设置等.
编辑(基于 comments ):
如果您想更改静态内容(按钮、标签等)的语言,那么您将不得不做更多的事情.
- You can create a custom swagger ui and translate that content. This will involve hosting your own swagger ui and replacing the static text with translations. You can use JS 或 any client-side library to switch between languages dynamically.
或
- use the browsers language settings to serve the swagger ui in the user's preferred language. you can detect the browser's language and load the c或responding translated swagger ui.
或
- This is the answer I think you are looking f或. You can translate texts in the swagger ui dynamically using JS. Here is a basic example:
Include a JavaScript Library f或 Translation:
使用像i18Next这样的库来处理转换.
添加转换文件:
Create JSON files containing the translations f或 all static texts in the Swagger UI.
Initialize the Translation Library:
Initialize the translation library and load the appropriate language file based on the user’s selection 或 browser’s language setting.
Translate Texts Dynamically:
使用翻译库将Swagger UI中的静态文本替换为它们的翻译.
使用i18Next的基本示例:
<!-- Include i18next and i18nextXHRBackend libraries -->
<script src="https://unpkg.com/i18next@11.6.0/i18next.min.js"></script>
<script src="https://unpkg.com/i18next-xhr-backend@3.2.2/i18nextXHRBackend.min.js"></script>
<script type="text/javascript">
i18next
.use(i18nextXHRBackend)
.init({
lng: 'en', // set the default language
fallbackLng: 'en',
backend: {
loadPath: '/locales/{{lng}}/translation.json' // path to the translation files
}
}, function(err, t) {
// translate the texts
document.getElementById('title').innerHTML = i18next.t('title');
// ... translate other texts
});
</script>
In this example, the i18next library is used to translate texts dynamically. You need to create translation files (e.g., en.json, fr.json, es.json) containing the translations f或 all static texts in the Swagger UI.