Reputation: 63
I would like to embed the swagger UI in a page on my blazor app. I am having a hard time finding examples of how to do this with razor pages. Does anyone have any examples doing this? I am usually more of a back end developer so struggling a bit getting this front end up and running.
Upvotes: 4
Views: 6358
Reputation: 45
For .NET 8, there is no need to use Startup.cs. You can embed swagger into Program.cs. Refer to this answer for more details - .NET8 Blazor and Swagger UI
Upvotes: 0
Reputation: 11
This is possible with JS Interop after rendering.
Setup Swagger as in Program.cs using their documentation. In Startup.cs, Include Swagger, but not swagger UI.
Then create your .razor
page like this
@inject NavigationManager NavigationManager
@page "/docs/view"
@inject IJSRuntime JS
<div id="swagger-ui"></div>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/swagger-ui.css" />
<script src="https://unpkg.com/[email protected]/swagger-ui-bundle.js" crossorigin></script>
<script>
window.loadswagger = function () {
const ui = SwaggerUIBundle({
url: '@($"{NavigationManager.ToAbsoluteUri("swagger/v1/swagger.json")}")',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis
]
})
window.ui = ui
}
</script>
@code {
private ElementReference divElement;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JS.InvokeVoidAsync("loadswagger");
}
}
}
This page will contain the embedded swagger. Be ready for some possible CSS conflicts between their stylesheet and your app's.
You can then apply your own CSS, and add more interaction between your app and the swagger UI.
Upvotes: 0
Reputation: 210
Although this is quite an old issue, I've decided to try and find the answer as I wanted to embed the Swagger UI into one of my pages myself.
It turns out that it is quite easy to do it!
All credits go to this repository - owner 'jsauve'.
Here are the steps that you need to do in order for it to show on your page:
Swashbuckle.AspNetCore
on your Blazor Server. services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
});
@page "/test"
<iframe src="swagger" style="width:90%;height:1200px;border:none;" />
Navigate to /test
from your e.g. MainLayout.razor. I hope it can help somebody because it certainly helped me.
Upvotes: 10