All Blog Posts

Addining Blazor WebAssembly To Existing ASP.Net MVC Project in ASP.Net Core 5


In this article, I have explained how we can make an existing ASP.Net MVC Application more powerful by integrating ASP.Net Web Assembly into it, I explained how to configure startup.cs file so we can run Blazor WebAssembly and ASP.Net MVC Together.

We just have to add following code snippets in startup.cs file.

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UMAR.BAL.Blog;
using UMAR.BAL.Messaging.Notify;
using UMAR.BAL.Messaging.Support;
using UMAR.DAL.BLOG;
using UMAR.DAL.SHARED;
using UMAR.DAL.SUPPORT;
using UMAR.IDENTITY.Data;
using UMAR.IDENTITY.Models;
using UMAR.IDENTITY.Services;

namespace UMARZONE.LMS
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration = configuration;
            HostEnvironment = env;
        }

        public IConfiguration Configuration { get; }
        public IWebHostEnvironment HostEnvironment { get; }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var builder = services.AddControllersWithViews();
#if DEBUG
            if (HostEnvironment.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation(options =>
                {
                    var Info = Path.GetFullPath(Path.Combine(HostEnvironment.ContentRootPath, "..\\", "UMAR.INFO"));
                    options.FileProviders.Add(new PhysicalFileProvider(Info));
                });
                
                builder.AddRazorRuntimeCompilation(options =>
                {
                    var Components = Path.GetFullPath(Path.Combine(HostEnvironment.ContentRootPath, "..\\", "UMAR.COM"));
                    options.FileProviders.Add(new PhysicalFileProvider(Components));
                });

                builder.AddRazorRuntimeCompilation(options =>
                {
                    var Identity = Path.GetFullPath(Path.Combine(HostEnvironment.ContentRootPath, "..\\", "UMAR.IDENTITY"));
                    options.FileProviders.Add(new PhysicalFileProvider(Identity));
                });
            }

#endif

            services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("ApplicationContextConnection")));

            services.AddDbContext<SharedDbContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("SharedConnection")));

            services.AddDbContext<SupportDbContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("UmarSupport")));

            services.AddDbContext<BlogDbContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("UmarBlog")));

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
                    .AddEntityFrameworkStores<ApplicationDbContext>();

            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = "/Identity/Account/AccessDenied";
                options.Cookie.Name = "MyInteriorMart";
                options.Cookie.HttpOnly = false;
                options.ExpireTimeSpan = TimeSpan.FromDays(10);
                options.LoginPath = "/Identity/Account/Login";
                // ReturnUrlParameter requires 
                //using Microsoft.AspNetCore.Authentication.Cookies;
                options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                options.SlidingExpiration = true;
            });
            // End:

            // Shafi: Customize Password And Other Policies
            services.Configure<IdentityOptions>(options =>
            {
                options.Password.RequireDigit = false;
                options.Password.RequireLowercase = false;
                options.Password.RequiredLength = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.SignIn.RequireConfirmedEmail = false;


                // Lockout settings.
                options.Lockout.MaxFailedAccessAttempts = 3;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers = false;

            });
            // End:

            // Shafi: Add Dependencies using Dependency Injection
            services.AddTransient<INotification, Notification>();
            services.AddTransient<ISupportService, SupportService>();
            services.AddTransient<IUserService, UserService>();
            services.AddTransient<IBlogRepository, BlogRepository>();
            // End:

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromDays(1);
            });

            // Shafi: Added to enable update razor view after page refreshing
            services.AddControllersWithViews();
            services.AddServerSideBlazor();
            services.AddRazorPages().AddRazorRuntimeCompilation();
            // End:

            // Shafi: Response Caching
            services.AddMemoryCache();
            // End:
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();

                // Begin: Enable Blazor WebAssembly
                app.UseWebAssemblyDebugging();
                // End:
            }
            else
            {
                app.UseExceptionHandler("/Home/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();


            // Begin: Enable Blazor WebAssembly
            app.UseBlazorFrameworkFiles();
            // End:


            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    const int durationInSeconds = 60 * 60 * 24;
                    ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                        "public,max-age=" + durationInSeconds;
                }
            });

            app.UseRouting();
            app.UseSession();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                // Shafi: Reference To UMAR.INFO
                endpoints.MapControllerRoute(
                       name: "INFO",
                       pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}",
                       new string[] { "UMAR.INFO.Controllers" }
                       );
                // End:

                // Shafi: Reference To UMAR.COM
                endpoints.MapControllerRoute(
                       name: "COMPONENT",
                       pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}",
                       new string[] { "UMAR.COM.Controllers" }
                       );
                // End:

                // Shafi: Reference To UMAR.IDENTITY
                endpoints.MapControllerRoute(
                       name: "IDENTITY",
                       pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}",
                       new string[] { "UMAR.IDENTITY.Controllers" }
                       );
                // End:

                // Shafi: Configure route for Areas
                endpoints.MapControllerRoute(
                    name: "areas",
                    pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                // End:

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();

                // Shafi: Identity/Account/Login current project
                // Note: Add this code in every startup file which reference to IDENTITY projct
                // If endpoints.MapRazorPages() not placed in startup.cs then identity will not work
                endpoints.MapRazorPages();
                // End:

                // Begin: Enable Blazor WebAssembly
                endpoints.MapFallbackToFile("index.html");
                // End:
            });
        }
    }
}

 


Post By Wasim Shaikh on Thursday 29 Apr, 2021

Recent Blog Posts

View All
Learn Software Clean Architecture

Professional AutoCAD Designing Training

It is a Mechanical, Civil And Electrical Industrial Designing Software. This software very important role playing in these industries. We are Teaching you 2D Designing in AutoCAD And also we have SOLIDWORKS And CATIA V5 3D Designing Software.

Learn Software Clean Architecture

Addining Blazor WebAssembly To Existing ASP.Net MVC Project in ASP.Net Core 5

In this article, I have explained how we can make an existing ASP.Net MVC Application more powerful by integrating ASP.Net Web Assembly into it, I explained how to configure startup.cs file so we can run Blazor WebAssembly and ASP.Net MVC Together

Learn Software Clean Architecture

Building Real-Time Web Application with SignalR

Building Real-Time web applications in ASP.Net Core 5 is now easy using SignalR, We can now establish bidirectional communication between the client and server using SignalR. It takes advantage of Websocket and HTML5 API for persistent connections.

Learn Software Clean Architecture

An Introduction To ASP.Net Core

It is a web development framework developed by Microsoft, it’s first version ASP.Net 1.0 was released in the year 2002 and last version was ASP.Net 4.7.1 which was released in 2017. It is a robust framework to develop cross platform apps