Forum Widgets
Latest Discussions
Convert the standard Blazor navigation menu to a collapsible icon menu
While I admittedly love Blazor I’ve always changed the out-of-the-box navigation menu that comes with it. It’s the first manoeuvre I pull when spinning up a new Blazor app, stripping out the purple gradient and getting it in, what I consider, a “blank slate state”. The other change I’ve wanted to make to the out-the-box look is one of those deluxe collapsible menus that leave just the icons showing. Anyone that’s used Azure DevOps will know what I’m talking about. I’ve included a picture to show DevOps example of what I’d like to see in my Blazor app. It gives a load of extra screen real estate which is always a priority for me in business applications particularly with complex or intensive workflows. Plus it gives the user the option to remove the text prompts once they are familiar with the system which is supported with carefully selected icon choices. As with most tasks that I assume will be an obvious solution I hit my search engine of choice and looked to avoid reinventing the wheel. However I found no source of pre-written changes to achieve this and was directed to fairly expensive third party controls to solve this one for me, which, being tight fisted, pushed me to do it for myself. Here I hope you save you the trouble of paying a pretty penny or having to wrestle the CSS into submission and provide a guide for producing a nice collapsible icon navigation menu by altering the existing out of the box menu in Blazor. In the following example I have left all the standard styling as is with the menu and just done the changes required to make the collapsible menu. The three files that require changes are MainLayout.razor, NavMenu.razor and NavMenu.razor.css. The code changes are shown below: Firstly the NavMenu.razor requires a bool value (IconMenuActive) to indicate whether the icon menu is showing or not, then wrap the text of the each NavItem in an if statement dependent on this bool. Then a method for toggling this bool and EventCalBack to send a bool to the MainLayout.razor for shrinking the width of the sidebar. Lastly there needs to be the control for switching menu views (I used the standard io icon arrows). NavMenu.razor <div class="top-row ps-3 navbar navbar-dark"> <div class="container-fluid"> <span class="oi oi-monitor" style="color:white;" aria-hidden="true"></span> @if (!@IconMenuActive) { <a class="navbar-brand" href="">The Menu Title Here</a> } <button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu"> <span class="navbar-toggler-icon"></span> </button> </div> </div> <div class="@NavMenuCssClass" @onclick="ToggleNavMenu"> <nav class="flex-column"> <div class="nav-item px-3"> <NavLink class="nav-link" href="" Match="NavLinkMatch.All"> <span class="oi oi-home" aria-hidden="true"></span> @if (!@IconMenuActive) { <label>Home</label> } </NavLink> </div> <div class="nav-item px-3"> <NavLink class="nav-link" href="counter"> <span class="oi oi-plus" aria-hidden="true"></span> @if (!@IconMenuActive) { <label>Counter</label> } </NavLink> </div> <div class="nav-item px-3"> <NavLink class="nav-link" href="fetchdata"> <span class="oi oi-list-rich" aria-hidden="true"></span> @if (!@IconMenuActive) { <label>Fetch data</label> } </NavLink> </div> </nav> </div> <div class="bottom-row"> <div class="icon-menu-arrow"> @if (!@IconMenuActive) { <span class="oi oi-arrow-left" style="color: white;" @onclick="ToggleIconMenu"></span> } else { <span class="oi oi-arrow-right" style="color: white;" @onclick="ToggleIconMenu"></span> } </div> </div> @code { //bool to send to MainLayout for shrinking sidebar and showing/hide menu text private bool IconMenuActive { get; set; } = false; //EventCallback for sending bool to MainLayout [Parameter] public EventCallback<bool> ShowIconMenu { get; set; } private bool collapseNavMenu = true; private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; private void ToggleNavMenu() { collapseNavMenu = !collapseNavMenu; } //Method to toggle IconMenuActive bool and send bool via EventCallback private async Task ToggleIconMenu() { IconMenuActive = !IconMenuActive; await ShowIconMenu.InvokeAsync(IconMenuActive); } } Next I add in a bit of CSS in to NavMenu.razor.css to put the arrow for toggling the menu at the bottom of the sidebar and a media query to make sure it doesn't show up in mobile view. The CSS classes added are .bottom-row and .icon-menu-arrow. NavMenu.razor.css .navbar-toggler { background-color: rgba(255, 255, 255, 0.1); } .top-row { height: 3.5rem; background-color: rgba(0,0,0,0.4); } .bottom-row { position: absolute; bottom: 0; padding-bottom: 10px; text-align: right; width: 100%; padding-right: 28px; } .icon-menu-arrow { text-align: right; } .navbar-brand { font-size: 1.1rem; } .oi { width: 2rem; font-size: 1.1rem; vertical-align: text-top; top: -2px; } .nav-item { font-size: 0.9rem; padding-bottom: 0.5rem; } .nav-item:first-of-type { padding-top: 1rem; } .nav-item:last-of-type { padding-bottom: 1rem; } .nav-item ::deep a { color: #d7d7d7; border-radius: 4px; height: 3rem; display: flex; align-items: center; line-height: 3rem; } .nav-item ::deep a.active { background-color: rgba(255,255,255,0.25); color: white; } .nav-item ::deep a:hover { background-color: rgba(255,255,255,0.1); color: white; } @media (min-width: 641px) { .navbar-toggler { display: none; } .collapse { /* Never collapse the sidebar for wide screens */ display: block; } } @media (max-width: 640px) { .bottom-row { display: block; } } Finally I add in the handler for the EventCallback to MainLayout.razor and a method to alter the width of the sidebar. MainLayout.razor @inherits LayoutComponentBase <div class="page"> <div class="sidebar" style="@IconMenuCssClass"> <NavMenu ShowIconMenu="ToggleIconMenu"/> </div> <main> <div class="top-row px-4"> <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a> </div> <article class="content px-4"> @Body </article> </main> </div> @code{ private bool _iconMenuActive { get; set; } private string? IconMenuCssClass => _iconMenuActive ? "width: 80px;" : null; protected void ToggleIconMenu(bool iconMenuActive) { _iconMenuActive = iconMenuActive; } } The final product of these little changes are shown in the pictures below: I'd love to hear if anyone has tackled this in a different way to me and if they've got any ideas on making it cleaner. Have yourselves a wonderful day, GavGavin-WilliamsFeb 26, 2023Copper Contributor73KViews10likes16CommentsCould not load file or assembly System.Data.SqlClient
Hello, I'm currently learning the ASP.NET Core-Web-API (.NET 6) system. I added a class-library (.NET Framework) (v4.8) as a DataAccessLayer to my project. There is a DAO class with a sql-query that uses Dapper and System.Data.SqlClient. just for example: var parameters = new { id }; using (SqlConnection connection = new SqlConnection("...")) { connection.Open(); return connection.ExecuteScalar<bool>(query, parameters); } ASP.NET Core-Web-API - Controller Lib - DAO-Class Now my Problem: When I try to invoke the method which contains this query: [HttpGet("foo")] public ActionResult<bool> Foo(DTO request) { var isOk = Lib.Dao.FetchSomething(request); return Ok(isOk); } , I'll get the following error on line 3: System.IO.FileNotFoundException: "Could not load file or assembly 'System.Data.SqlClient, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified." My lib has the reference to System.Data (4.0.0.0) and System.Data.SqlClient (4.6.1.3). Why do .net tries to search the version 0.0.0.0? Why does this doesn't work? This should work (worked for me on .NET WebForms) Regards.alex-1337Oct 10, 2022Copper Contributor68KViews0likes5CommentsOpen Source ASP.NET 8 MVC 5 Admin Template - Sneat
Hi All, Sharing here Sneat Free Asp.NET Core MVC Admin Template. If you’re a developer looking for the latest Free ASP.NET Core 8, MVC 5 Admin Panel Template that is developer-friendly, rich with features, and highly customizable look no further than Sneat. Incredibly versatile, this Free ASP.NET Dashboard also allows you to build any type of web application. For instance, you can create: SaaS platforms Project management apps E-commerce backends CRM systems Analytics apps Banking apps Education apps Fitness apps & many more. Features: Based on ASP.NET Core 8, MVC 5 UI Framework Bootstrap 5 Vertical layout 1 Unique Dashboard 1 Chart library SASS Powered Authentication Pages Fully Responsive Layout Organized Folder Structure Clean & Commented Code Well Documented You can check the GitHub repo as well: https://github.com/themeselection/sneat-bootstrap-html-aspnet-core-mvc-admin-template-free Hope you all like it.Abhi_005Jan 11, 2024Copper Contributor20KViews1like0CommentsBlazor WASM PWA – Applications updates, cache busting with notification or force refresh
My team is currently working on a Blazor application and after several bouts of confusion between developers and testers we stuck a version number on the home screen and discovered the updates weren’t going out to everyone as we were expecting. We ended up with several people on different versions of the application and fortunately we spotted this issue early in development. I’ve put together the options and info I’ve found while trying to find a solution to this that works for our particular situation in hopes that it will help someone else dealing with this and hopefully open a discussion on how people are handling this issue and find any alternative solutions. To look at what was happening behind the scenes, I set up a simple WASM PWA on .NET7 and have it hosted on an Azure App Service. I stuck a version number on the home page so I can easily see when the update has taken place. The behaviour: Blazor WASM PWA applications load the application into the browser based on the cache pulled in by the service workers (Javascript assets that act as a proxy between browsers and web servers for offline support and performance). In dev tools you can see what’s in the cache storage for the app (go to dev tools > application tab > cache storage). The picture below shows that the cache contains “blazor-resources” and “offline-cache”. The “offline-cache” is the important one that determines what the site is displaying and on pushing an update the “blazor-resources” is unaffected so for this purpose can be ignored. Now the standard behaviour on pushing an update to the app is that the service worker will install the new app cache in the background and enter the “waiting” state and will not activate the newly cached app until the current application service worker is released, by either closing the browser or hard refreshing the app (Ctrl + F5). This behaviour is by design to prevent having two tabs open with different versions of the application running at once. However users may never close the application or browser or whatever and that would mean they could be running long retired versions of your application for an indeterminant length of time. Below you can see the cache storage after an update has been pushed stacking up the old and new version of the offline-cache. Once the service worker has been released then the old cache is removed the latest will be activated. This will then display the new version of the app. The solution: Now, what if we want to change this behaviour to either prompt and update or force one? Either way we will want to remove the need to close browsers or hard refresh as that can be a bit of a tricky one to get end users to get on board with. The service workers actually have a method that can skip the “waiting” stage of the service worker lifecycle clear the old cache and activate the latest. This is the SkipWaiting method. In the Blazor solution there is the service-worker.published.js file found in the wwwroot folder. This file contains the methods for the service worker. In this file there is a OnInstall method and can be modified to the following adding in the SkipWaiting method: async function onInstall(event) { console.info('Service worker: Install'); self.skipWaiting(); // Fetch and cache all matching items from the assets manifest const assetsRequests = self.assetsManifest.assets .filter(asset => offlineAssetsInclude.some(pattern => pattern.test(asset.url))) .filter(asset => !offlineAssetsExclude.some(pattern => pattern.test(asset.url))) .map(asset => new Request(asset.url, { integrity: asset.hash, cache: 'no-cache' })); await caches.open(cacheName).then(cache => cache.addAll(assetsRequests)); } This additional line will now allow a standard refresh to update the application rather than requiring a hard refresh or closing the browser completely. When looking at the cache storage when an update is pushed you will see the second cache appear then the old cache disappear immediately. Note: Adding this behaviour will overwrite the intended behaviour and allow the potential of different version of the application running in different tabs. However we can look at avoiding that by forcing update later. Next, regardless of whether we want to prompt the user for an update or force it on them, we need a way of letting the site know it needs an update. My javascript is less than brilliant so I’ve used a solution by Wouter Huysentruit, full description here: https://whuysentruit.medium.com/blazor-wasm-pwa-adding-a-new-update-available-notification-d9f65c4ad13 This involves adding a js file called sw-registrator.js to the wwwroot folder that will allow an event to be triggered that can link to updating the site: window.updateAvailable = new Promise((resolve, reject) => { if (!('serviceWorker' in navigator)) { const errorMessage = `This browser doesn't support service workers`; console.error(errorMessage); reject(errorMessage); return; } navigator.serviceWorker.register('/service-worker.js') .then(registration => { console.info(`Service worker registration successful (scope: ${registration.scope})`); registration.onupdatefound = () => { const installingServiceWorker = registration.installing; installingServiceWorker.onstatechange = () => { if (installingServiceWorker.state === 'installed') { resolve(!!navigator.serviceWorker.controller); } } }; }) .catch(error => { console.error('Service worker registration failed with error:', error); reject(error); }); }); window.registerForUpdateAvailableNotification = (caller, methodName) => { window.updateAvailable.then(isUpdateAvailable => { if (isUpdateAvailable) { caller.invokeMethodAsync(methodName).then(); } }); }; Within index.html in the wwwroot folder we will need to register this new file instead of the service-worker.js. So we need to replace the reference to service-worker.js with the following: <script src="sw-registrator.js"></script> This will now raise an event once the cache refresh happens that can be used to trigger a prompt on the application or a refresh of the application. Now we need a razor component that will listen for the event and either throw up a refresh prompt or just force a refresh. Firstly I’ll do the prompt. For this make a new razor component and add the following code: @inject IJSRuntime _jsRuntime @inject NavigationManager uriHelper @if (_newVersionAvailable) { <button type="button" class="btn btn-danger shadow floating-update-button" onclick="window.location.reload()"> A new version of the application is available. Click here to upgrade. </button> } @code { private bool _newVersionAvailable = false; protected override async Task OnInitializedAsync() { await RegisterForUpdateAvailableNotification(); } private async Task RegisterForUpdateAvailableNotification() { await _jsRuntime.InvokeAsync<object>( identifier: "registerForUpdateAvailableNotification", DotNetObjectReference.Create(this), nameof(OnUpdateAvailable)); } [JSInvokable(nameof(OnUpdateAvailable))] public Task OnUpdateAvailable() { _newVersionAvailable = true; StateHasChanged(); return Task.CompletedTask; } } I personally like a red bar across the top as it’s very attention grabbing so you can add the following css file called WhateverYouCalledTheComponent.razor.css: .floating-update-button { position: relative; top: 0; padding: 1rem 1.5rem; width: 100%; } This component can then be placed at the top of MainLayout.razor above the body to ensure it appears anywhere on the app the user happens to be. This will then produce the following result once an update is pushed out: Once the banner is clicked, it will reload the site and the new update will be running. This is the setup that I will be implementing on my teams project as I wouldn’t want the site to force updates in case a user was in the middle of data entry. However if a forced refresh is desired, it’s a quick change to the razor component to allow that. Change the components code to the following: @inject IJSRuntime _jsRuntime @inject NavigationManager uriHelper @code { protected override async Task OnInitializedAsync() { await RegisterForUpdateAvailableNotification(); } private async Task RegisterForUpdateAvailableNotification() { await _jsRuntime.InvokeAsync<object>( identifier: "registerForUpdateAvailableNotification", DotNetObjectReference.Create(this), nameof(OnUpdateAvailable)); } [JSInvokable(nameof(OnUpdateAvailable))] public Task OnUpdateAvailable() { uriHelper.NavigateTo(uriHelper.Uri, forceLoad: true); StateHasChanged(); return Task.CompletedTask; } } Now on pushing an update you will see that the update is installed in the cache and once the event is triggered the old cache is removed and the site reloads wherever it happens to be. I’d be really interested to hear other peoples takes on this or if they’ve found other methods of achieving this, I’ve scoured the web and this was the combination of the best methods I came across but certainly open to improvement.Gavin-WilliamsSep 07, 2023Copper Contributor12KViews0likes5CommentsOpen Source Materio Asp.NET Core MVC Admin Dashboard Template
Hi All, Sharing here Materio Free Asp.NET Core MVC Admin Template. If you’re a developer looking for the latest Free ASP.NET Core 8, MVC 5 Admin Panel Template that is developer-friendly, rich with features, and highly customizable look no further than Sneat. Incredibly versatile, this Free ASP.NET Dashboard also allows you to build any type of web application. For instance, you can create: SaaS platforms Project management apps E-commerce backends CRM systems Analytics apps Banking apps Education apps Fitness apps & many more. Features: Based on ASP.NET Core 8, MVC 5 UI Framework Bootstrap 5 Vertical layout 1 Unique Dashboard 1 Chart library SASS Powered Authentication Pages Fully Responsive Layout Organized Folder Structure Clean & Commented Code Well Documented You can check the GitHub repo as well: https://github.com/themeselection/materio-bootstrap-html-aspnet-core-mvc-admin-template-freeSen_DotNetJan 12, 2024Copper Contributor11KViews1like0CommentsVS2022 Bootstrap 5 No intellisense for asp.net core MVC project
Hello, I just downloaded VS2022 and created an asp.net core web app MVC project. First thing I noticed was it uses bootstrap 5, but does not have intellisense. Nothing special going on. 1. Create new project 2. Select asp.net Core Web App (Model-View-Controller) 3. Edit one of the provided .cshtml files 4. Check for intellisense, i.e. <div class="text-success"> Any suggestions?RickM2006Jan 05, 2022Copper Contributor9.1KViews1like2CommentsASP.Net Core 6 Web App - Fails to connect to database after published to on-prem IIS
Dear Community, I started to learn .Net core and entity framework, and its great. I built a small webapp as a test with a database (SQL LocalDB) and locally on my dev machine, it works fine. I publish to a folder location, then copy locally to a Windows 2019 Server and added a website on the server's IIS. The app will run the razor pages without a model, but the page that serves the model to add data or view data from the SQL database fails and the error is weird and it says there is no server found and cannot authenticate NT Authority\System. I made sure that SQL server express is installed and I can connect, I made sure localDB was added as a feature to the sqlexpress instance, etc., etc., My question is, do I have to do anything funky like wear a foil paper hat, to get this to work? I cant seem to find any documentation at all and youtube tutorials go through all the motions except publishing the app. Any help will be greatly appreciated.Hugo O. OrnelasApr 18, 2023Copper Contributor5.9KViews1like5CommentsASP.NET webforms - compilation/httpruntime configuration in asp.net web.config
Will having the following configuration in asp.net/webform web.config file work without security issues due to lack of support after April 2022 for .NET Framework v4.5.2, 4.6 and 4.6.1? ie - compilation is v4.8, httpruntime is v4.5. <compilation debug="true" targetFramework="4.8"> ... </compilation> <httpRuntime targetFramework="4.5"/>richard1245Nov 04, 2021Copper Contributor5.5KViews0likes1CommentNo Registered Service for IEmailSender
Hello all, I am using ASP.Net Core Web API (.Net Core 😎 to create a web app and API, when i added default Identity and Areas Pages i am getting an error for IEmailSender Service not beeing registered even though i dont need and have registered a mock class for it. Thank you Program.cs using Microsoft.AspNetCore.Identity; using Microsoft.OpenApi.Models; using Microsoft.EntityFrameworkCore; using ProMateAPI.Data; using ProMate.Library; using Swashbuckle.AspNetCore.Filters; using ProMateAPI.Utility; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.Extensions.DependencyInjection; var builder = WebApplication.CreateBuilder(args); // Add services to the container. var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); builder.Services.AddDatabaseDeveloperPageExceptionFilter(); // this would be enabled if we only needed the defaults for users and such //builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) // .AddEntityFrameworkStores<ApplicationDbContext>(); // builder.Services.AddDbContext<TContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default"))); builder.Services.AddDbContext<ProMateContext>(); builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(options => { options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey, }); options.OperationFilter<SecurityRequirementsOperationFilter>(); }); /* * options => { options.SignIn.RequireConfirmedAccount = false; options.SignIn.RequireConfirmedAccount = false; } * * */ builder.Services.AddScoped<IEmailSender, MyEmailSender>(); builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>(); ////builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<ApplicationDbContext>(); builder.Services.AddAuthentication(); builder.Services.AddAuthorization(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseMigrationsEndPoint(); } 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.MapIdentityApi<IdentityUser>(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.MapRazorPages(); app.Run(); ------------- MyEmailSender.cs using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace ProMateAPI.Utility; public class MyEmailSender : IEmailSender { public Task SendEmailAsync(string email, string subject, string htmlMessage) { return Task.CompletedTask; } } ----------------- Register.html.cs // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Text.Encodings.Web; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Logging; using ProMateAPI.Utility; namespace ProMateAPI.Areas.Identity.Pages.Account { public class RegisterModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly UserManager<IdentityUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; private readonly IUserStore<IdentityUser> _userStore; private readonly IUserEmailStore<IdentityUser> _emailStore; private readonly ILogger<RegisterModel> _logger; //private readonly IEmailSender _emailSender; // IEmailSender emailSender public RegisterModel( UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager, IUserStore<IdentityUser> userStore, SignInManager<IdentityUser> signInManager, ILogger<RegisterModel> logger ) { _userManager = userManager; _roleManager = roleManager; _userStore = userStore; _emailStore = GetEmailStore(); _signInManager = signInManager; _logger = logger; //_emailSender = emailSender; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [BindProperty] public InputModel Input { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public string ReturnUrl { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public IList<AuthenticationScheme> ExternalLogins { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class InputModel { /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public async Task OnGetAsync(string returnUrl = null) { // creates missing roles if (!_roleManager.RoleExistsAsync(SD.Roles.Customer.ToString()).GetAwaiter().GetResult()) { foreach (var r in Enum.GetValues(typeof(SD.Roles))) { _roleManager.CreateAsync(new IdentityRole(r.ToString())).GetAwaiter().GetResult(); } } ReturnUrl = returnUrl; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = CreateUser(); await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl }, protocol: Request.Scheme); //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", // $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }); } else { await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return Page(); } private IdentityUser CreateUser() { try { return Activator.CreateInstance<IdentityUser>(); } catch { throw new InvalidOperationException($"Can't create an instance of '{nameof(IdentityUser)}'. " + $"Ensure that '{nameof(IdentityUser)}' is not an abstract class and has a parameterless constructor, or alternatively " + $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml"); } } private IUserEmailStore<IdentityUser> GetEmailStore() { if (!_userManager.SupportsUserEmail) { throw new NotSupportedException("The default UI requires a user store with email support."); } return (IUserEmailStore<IdentityUser>)_userStore; } } }r00terAF23Mar 28, 2024Copper Contributor5KViews0likes1Comment.NET 6 Web Hosting Bundle
Will there be a new version of the Web Hosting Bundle (currently at 5.0.11) with the full release of .Net 6 or does the current version work for .NET 6? I have an ASP.NET Core site running (locally) on .NET6 rc2 but I'm terrified to publish it for fear that the current version of the web hosting bundle won't run it. Please advise.stevenjamesfrankNov 08, 2021Copper Contributor4.9KViews0likes0Comments
Resources
Tags
- ASP.NET Core152 Topics
- ASP.NET (Classic)82 Topics
- Web API63 Topics
- Blazor62 Topics
- mvc55 Topics
- Razor Pages35 Topics
- IIS.NET29 Topics
- security26 Topics
- SignalR6 Topics
- community1 Topic