We have a legacy application on ASP.NET Web Forms (version .NET 4.8), now we want to shift it to latest tech stack Blazor using Server Hosting Model only (version .NET 8). I am facing issues in embedding the Blazor Server components in Web Forms. Is there any better way to embed the component in Web Forms except Iframe, or WASM files.
Currently, I am using the Event Driven architecture to create a communication between these application.
Web Form application initializes the Events (which are custom, and created in events.js file), and then send the JSON data to the Blazor Component.
While the Blazor component subscribe the event using addEventListener function.
Important Note: Blazor will only listen the event from web forms, when blazor component itself embed in the web form.
I am trying to add the dynamically the Blazor Component in Web forms by using API endpoint that raised from Blazor Component and then send to web forms.
Here is the overview of my code:
WebForm.aspx:
<form id="form1" runat="server">
<h2>Web Forms Page with Blazor Address Book Component</h2>
<!-- Placeholder for Blazor component -->
<div id="blazorAddressBook"></div>
</form>
<!-- Load the Blazor component dynamically from the Blazor Server -->
<script src="https://localhost:blazorPort/api/BlazorAddressBook?action=initialize&htmlNode=blazorAddressBook"></script>
BlazorAddressBook API Controller:
[Route("api/[controller]")]
[ApiController]
public class BlazorAddressBookController : ControllerBase
{
[HttpGet]
public IActionResult Get(string action, string htmlNode = "body")
{
string script = @"
if (!window.blazorInitialized) {
window.blazorInitialized = false; // Only set this once, if it doesn't exist
window.addEventListener('load', function() {
if (!window.blazorInitialized) {
window.blazorInitialized = true;
var script = document.createElement('script');
script.src = 'https://localhost:blazorport/_framework/blazor.server.js';
script.onload = function () {
Blazor.start().then(function () {
console.log('Blazor Initialized');
window.blazorInitialized = true; // Set to true only after initialization is successful
}).catch(function (err) {
console.error('Blazor initialization failed:', err);
});
};
document.body.appendChild(script);
}
});
}
";
return Content(script, "text/plain");
}
}
Program.cs:
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowWeb", builder =>
{
builder.WithOrigins("https://localhost:webformPort")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
app.UseCors("AllowWeb");
Currently add the moment I am just trying to embed the Blazor Server component in ASP.NET Web forms.
Here is the issue: