Embed Blazor SERVER Component in ASP.NET WEB Forms #58607
Unanswered
DStarts23
asked this question in
Show and tell
Replies: 1 comment
-
I read that |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi, I need your guys suggestion or solution about embedding of Blazor Components in Web Forms application.
Versions:
Blazor Version: .NET Core 8
Web Forms Version: .NET framework 4.8
Strategy:
I am using the dynamic way to load the Blazor components in web forms by creating the API Endpoints in Blazor application that will hit when someone tries to fetch the Blazor component from Web Forms.
Blazor Server Application:
In
program.cs
file, I have configured all the respected builders, as:`// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton();
//CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowWebFormsOrigin",
builder =>
{
builder.WithOrigins("https://localhost:44306") // Your Web Forms app URL
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithExposedHeaders("Content-Disposition"); // Important for WebSockets
}
);
});
//Setting timeout configuration
builder.Services.AddServerSideBlazor()
.AddCircuitOptions(options =>
{
options.DetailedErrors = true;
options.DisconnectedCircuitMaxRetained = 100;
options.DisconnectedCircuitRetentionPeriod = TimeSpan.FromMinutes(5);
});
builder.Services.AddSignalR(hubOptions =>
{
hubOptions.ClientTimeoutInterval = TimeSpan.FromMinutes(2); // Increase timeout interval
hubOptions.HandshakeTimeout = TimeSpan.FromSeconds(30); // Increase handshake timeout
hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(15); // Send keep-alive pings
});
builder.Services.AddServerSideBlazor()
.AddHubOptions(options =>
{
options.MaximumReceiveMessageSize = 1024 * 1024; // 1 MB buffer size
});
builder.Services.AddControllers();
builder.Logging.SetMinimumLevel(LogLevel.Debug); // Enable debug level logging
builder.Logging.AddConsole(); // This logs to the console for development purposes
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseHsts();
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
ctx.Context.Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:44306");
}
});
app.UseRouting();
// Configure the HTTP request pipeline
app.UseCors("AllowWebFormsOrigin"); // Apply CORS policy
app.MapControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
app.Run();`
Created an API Controller,
ComponentController.cs
:[Route("api/[controller]")]
[ApiController]
[EnableCors("AllowWebFormsOrigin")]
public class ComponentController : ControllerBase
{
[HttpGet]
public IActionResult GetCounterComponentHtml()
{
// Return some pre-rendered HTML or instructions on loading Blazor.
return Ok("
Counter Component
}
}
The component I want to load in the Web Forms application is,
Contact.razor
:`@page "/contact"
Address Book
List of contacts will appear here.
Existing Contact List is:
@foreach (var contact in myContacts) {- @contact.Name - @contact.Email
}
@code {
private List myContacts = new List()
{
new ContactAd { Name = "Alice Smith", Email = "[email protected]" },
new ContactAd { Name = "Bob Johnson", Email = "[email protected]" },
new ContactAd { Name = "Charlie Brown", Email = "[email protected]" }
};
}`
And in Web Forms application, receiving this endpoint as,
Data.aspx
:`
<title>Embedding Blazor in Web Forms</title>
Blazor Address Book Component in Web Forms
<script> // Fetch Blazor component HTML from the API fetch('https://localhost:7102/api/component/contact') //Blazor URL .then(response => response.text()) .then(html => { // Inject the HTML into the Web Forms page document.getElementById('blazor-contact').innerHTML = html; // Ensure Blazor is not already initialized if (!window.Blazor) { // Dynamically load the Blazor script and set autostart to false var script = document.createElement('script'); script.src = 'https://localhost:7102/_framework/blazor.server.js'; script.setAttribute('autostart', 'false'); // Ensure Blazor does not auto-start script.onload = function () { //Manually start Blazor after loading the script Blazor.start({ logLevel: 'Debug', }).then(() => { console.log('Blazor started successfully.'); }).catch(error => { console.error('Error starting Blazor:', error); });You might will notice I am passing the app in API Get Contact, and saying I want to load the component, Just for testing purpose, first I want to make sure that the app starts loading then I can change it to
balzor.root.component
type and can call any component I want.The errors I am encountering is:
In screenshot#02, request URL in Blazor is saying
ws
but it is usinghttps
,And on web forms it is referring to the
wss
of Blazor URL, I have a confusion here, why it is failing to load that component/app in web forms due to web socket connection.Beta Was this translation helpful? Give feedback.
All reactions