razor pages
36 TopicsVS2022 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?9.3KViews1like2CommentsNo 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; } } }5.3KViews0likes1CommentCore 5 Razor Pages redirect to custom location login page
Hi, I have created a login page that stands on the root of the application instead of the standard /Account/Login. When attempting to access a page that as the [Authorize] annotation, I keep getting redirected to the standard login location instead of my custom one. How can I change this so that when the user is not authenticated he gets redirected to /Login instead of /Account/Login?Solved3.9KViews0likes1CommentHow to localize Routes in Core 5 MVC and/or Razor Pages
Hi, I've been developing websites and applications in webforms for the last 15 years. With the appearance of URL Routing, i've been using it for SEO purposes, allowing multilingual websites to change the URLs according to the user selected language, while calling the same route. This allows me to have localized routes call the same webform. Ex: mydomain.com/{language}/{category_meta_id}/{product_meta_id} mydomain.com/en/games/my-game mydomain.com/pt/jogos/o-meu-jogo the above route can call the same webform, for instance ProductDetail.aspx, and have it gather the parameter 'language' to decide the language to load, 'category_meta_id' to understand the area to call that must be challenged on the database along with the selected language, and the 'procuct_meta_id' that also uses the language to challenge the database in order to determine which content to load. This is supported by a DB table structure like: Category -CategoryId (PK) -IsActive CategoryText -CategoryTextId (PK) -CategoryId (FK) -Language -MetaId -Title -ContentText Product -ProductId (PK) -CategoryId (FK) -ProductImage -IsActive ProductText -ProductTextId (PK) -ProductId (FK) -Language -MetaId -Title -ContentText Bottom line is, i can have a localized URL call the same exact product on the selected language while using one single form to handle the request. I've been considering making the transition to either Core5 MVC or Core5 Razor Pages, but due to the way both these technologies handle routing, i'm not sure how, or even if it is possible to have the same URL approach without having to either duplicate folders in case of the Razor Pages, or duplicate controllers and views in the case of MVC. Making this transition also seems to implicate loosing the capacity of determining all the URL parts from the database, which currently allows content admins to create categories and/or products on the fly without having to code new Controllers and Views for each language of a new category or product. For instance, if a content admin wishes to add a new product with the title 'Game 2' in English and 'Jogo 2' in Portuguese, he/she only needs to use a form on the backend to create the new product, first in one language, then on the other under the same ProductId, allowing that the URLs mydomain.com/en/games/game-2 and mydomain/pt/jogos/jogo-2 to call the same ProductDetail.aspx webform. The same could be done to create a new category, for instance 'Toys' / 'Brinquedos'. How can i achieve the above on MVC or Razor pages? It seems to me that the content admin would have to create new controllers and views, or folders and pages in the case of Razor Pages, for each product or category while also having to duplicate them for each language... am I missing something? Can someone give me a hand on this? Thanks2.1KViews0likes2CommentsCapturing data of 1 page in another page using razor view and dotnet core
Hello Everyone, I am trying to build a mentorship software in dotnet core and I am having this problem. What I intend to do is that, when a mentee wants to register on the platform they put their Name, email and choose from list of career (career being generated as a drop down from another table from the db or can also be generated as drop down from enum). So, when mentee clicks next, the system routes them to another page where they can choose mentor based on the career they have chosen and then when they choose a mentor, they should have a button to post the information from previous page (Name and email ) and the Id of the selected mentor in Page 2. The problem I am having is that the data from the first page(The page where a new mentee inputs their email and name) is lost when it routes to the second page(the page to choose a mentor). So, I want a way to capture the data in the first page so that I can post these data alongside the data in the second page to the database (Mentee Table) Mentor is a foreign key in the mentee table because the schema is designed so that a mentee can only have 1 mentor but 1 mentor can have multiple mentees.1.8KViews0likes1CommentBest practice for inject Dependency service in Blazor
I am in process to start develop an ERP Application in Blazor server. I am new in Blazor technology. I want suggestion in DI. I have a class called Setting. This class is used for store application’s setting at the time of user login and consume it in at every component level. And this class have reference type multiple properties. I want suggestion that what is best practice to handle these properties. There is multiple ways to handle these property. please suggest me which is best way or any new way is also welcome. Base Class public class CompanyBase { public int ID { get; set; } public string? Name { get; set; } } public class OptionBase { public int Option1 { get; set; } public string? Option2 { get; set; } } Way No 1 public class Setting { public CompanyBase User { get; } = new (); public OptionBase Option { get; } = new(); } Program.cs builder.Services.AddTransient<Setting>(); FetchData.razor @inject Setting setting Way No 2 public class Setting { public CompanyBase User { get; init; } public OptionBase Option { get; init; } public Setting(CompanyBase user, OptionBase option) { User = user; Option = option; } } Program.cs builder.Services.AddTransient<CompanyBase>(); builder.Services.AddTransient<OptionBase>(); builder.Services.AddTransient<Setting>(); FetchData.razor @inject Setting setting Way No 3 No Setting Class Program.cs builder.Services.AddTransient<CompanyBase>(); builder.Services.AddTransient<OptionBase>(); FetchData.razor @inject CompanyBase Company @inject CompanyBase Option1.7KViews0likes1CommentBlazor Server App with Dynamic CultureInfo Saved in Cookie don't work in iFrame anymore
Hi, I can't share my own app for nda issue but I found this one which shows exactly the same issue https://github.com/tossnet/Blazor-Localization This app displays a page with a CultureSwitcher component to select between 5 languages. When you select a language, I can see both the page+dropdown refreshed with the selected language value. Now, you embed the Url of this app inside a new app's page inside an iFrame and nothing works anymore. The cookie mecanism doesn't save or/and load the value anymore. This was working perflecly in net+core+3.1 and 5.0 but no more in net+core+6. Is something change in security or cors or ???? Thanks in advance for any tips -Vince1.5KViews0likes2CommentsLooking for recommendations for hosting ASP.NET web apps
I've been with an ASP.NET web hosting service for several years. However, the service provided has declined in the last couple of years. So, I started looking for a new, inexpensive, web hosting service. This is for my side business, which doesn't attract that much traffic. Yes, I'm sure that Azure would do, but like I said I'm trying to keep costs down. Naturally, I started searching. I've come across a couple of "Top 10 hosting services for 2023". I've spent about three weeks looking at different ones. I want to publish my ASP.NET Core both from Visual Studio and Azure DevOps Services, using the Azure DevOps FTP task if necessary. My website is currently written in .NET 6. This search experience has not been a pleasant experience. Some services I've spoken to said that because I am working with ASP.NET, then it can only run on Windows, and therefore I couldn't use their service, since they are a Linux only provider (mostly WordPress). I have told two of these web hosting services that ASP.NET Core can run on Linux. I even shared links from Microsoft that ASP.NET Core can run on Linux, Mac, and Windows. In both cases their response was disbelief and a refusal to discuss the topic further with me. Since it seems that many web hosting services have a mindset that refuse to accept the idea that anything from Microsoft can run on Linux, I decided to go back to researching web hosting companies that offer ASP.NET on Windows (both traditional .NET Framework varieties as well as .NET Core with .NET 5, 6, and 7). I settled on one, but they insist that I must allow them to re-register the domain I've owned for 10+ years. They will not allow me to upload my website to them until I've unlocked my website from the domain registrar I use. I've told them, at least three times, that I am satisfied with the domain registrar I have and only need a web hosting provider. They won't hear of it and refuse to go any further with me. So, once again I'm back to searching for a web hosting company for small businesses, that is inexpensive (OK, cheap), that I might be able to have multiple domains on. Therefore, I'd appreciate recommendations from this community, please.1.4KViews0likes8CommentsGetting Values from EF Core Context with Dynamic Calls to Tables.
I'm working in EF Core 5 with Razor pages connecting to SQL Server and am trying to develop a generic form that handles multiple lookup tables. So I'm trying to dynamically access the tables in my context. My problem is that I can access the Properties (column names) of the tables themselves but I can't access the keys of the IEnumerable object when I pass it. I have a dictionary of all the tables that passes the context to the form. I can see the data is there along with the keys. How do I reach the keys (specifically CenterTypeId and CenterType in the images provided) so I can get my data without having to pass a select in my context dictionary? Some of the tables I'm going to be using have more than 2 columns and I'll need access to all the data in them. The only properties in the dbSet IEnumerable variable that I am able to access are the Entity Type and the Tracking.LocalView1.3KViews0likes1Comment