Embedding of Blazor Server Component in Web Forms

Aima Maqsood 45 Reputation points
2024-10-18T07:27:11.24+00:00

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:

Developer technologies .NET Blazor
Developer technologies ASP.NET Other
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-10-18T16:23:29.5+00:00

    Blazor WASM is better designed to be hosted on an html page. Blazor server expects to render the index.html file, and includes pre-render bits. You can probably reverse engineer (be sure to disable pre-render), but it could break with the next release.

    also as noted, a webform postback will reload the blazor app. also the blazor server app and webform will not share session information.

    to implement communication you would need to use blazor custom events:

    https://learn.microsoft.com/en-us/aspnet/core/blazor/components/event-handling?view=aspnetcore-8.0

    you are probably better off converting whole pages to blazor rather than part of a page.

    note: in the past MS suggested creating blazor web components, but support for this seems to have tapered off. here is project that may help you:

    https://github.com/ostomachion/blazor.webcomponents


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.