Troubleshooting Portable Object Localization in Blazor server app with .NET 6 - blazor-server-side

Trying to configure portable object localization in Blazor server app with .NET 6 following instructions from video "ASP.NET Community Standup - Localizing the .NET Website" from minute 23:54 on, but I can't get it working.
At its simplest stage, the video recommends next steps:
append .AddViewLocalization() to Program.cs builder.Services.AddRazorPages() line.
add the line app.UseRequestLocalization() to Program.cs after app.UseRouting()
on any page (index.razor in my case) add #using Microsoft.AspNetCore.Mvc.Localization and #inject IViewLocalizer T
change any string into its localizable version as Hello, world! into #T["Hello, world!"]
But it throws a System.NullReferenceException in #T["Hello, world!"]
Any ideas? I could not find any further documentation for Po files in Blazor server apps
My Program.cs:
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using TestOrhard.Data;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages().AddViewLocalization();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseRequestLocalization();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
My Index.razor:
#page "/"
#using Microsoft.AspNetCore.Mvc.Localization
#inject IViewLocalizer T
<PageTitle>Index</PageTitle>
<h1>#T["Hello, world!"]</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />

Related

swagger/index.html shows a blank page (asp.net core)

I am writing a web api in ASP.NET CORE for the data models Package and Content. They are originally from MSSQL so I connected to the db server successfully. After writing http requests in the controllers, when I ran the project to test, it takes me to swagger/index.html that shows a blank page, I have no idea why.
Here is my program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
//OperationsContext is a db context that has both content and package dbcontext
builder.Services.AddDbContext<OperationsContext>(x => x.UseSqlServer(connectionString));
/*builder.Services.AddMvc();
builder.Services.AddHttpContextAccessor();*/
builder.Services.AddScoped<IContentRepository, ContentRepository>();
builder.Services.AddScoped<IPackageRepository, PackageRepository>();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI(c =>
{
if (app.Environment.IsDevelopment() || app.Environment.IsProduction())
{
c.SwaggerEndpoint("/swagger/Package/swagger.json", "Package v1");
}
else
{
// To deploy on IIS
c.SwaggerEndpoint("/swagger/Package/swagger.json", "Package v1");
}
});
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
I am assuming it's the program.cs, but there are no issues when I ran it. Does anyone know why?
Swagger UI does not support Internet Explorer. Use Chrome, Firefox, Safari, or Edge instead.

Localhost not found after migrating application from .net 5 to .net 6

I am unable to run my web application project in IIS Express after migrating from .net 5 to .net 6. I get an error stating that "the localhost page can't be found."
From what I've been able to learn, I have gone through the proper steps to migrate between target frameworks. I have changed the target framework to .net 6 in application properties, and I have updated all affected NuGet packages using the NuGet Pkg Manager. No errors are shown when I build the project, and I have ensured Visual Studio is updated to the latest version, 17.2.5 as of this writing.
The IIS Settings in my launchsettings.json file are as follows:
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:35317",
"sslPort": 44352
}
}
and I do have an Index view return in my home controller. Yet I still get the error that
No webpage was found for the web address: https://localhost:44352/
when I run the application.
I am retaining the "old" hosting model of Startup.cs and Program.cs from the .Net 5 build to save time, as I understand per Microsoft that this is acceptable. No changes have been made to the code in either of those files.
What am I missing?
EDIT: My Program.cs code is below, by request of #adrianMoskal
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
EDIT 2:
Per #adrianMoskal, I updated my Program.cs file to .NET 6 standard. It now looks like this:
var builder = WebApplication.CreateBuilder(args);
// Add DB Contexts and Services here
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Unfortunately, the error persists.
I created a new project to migrate from .net 5 to .net 6, but no problem, it works fine, I will show you the complete steps:
.csproj:
change Version like below:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<!--<TargetFramework>net5.0</TargetFramework>-->
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>_2022070802</RootNamespace>
<CopyRefAssembliesToPublishDirectory>false</CopyRefAssembliesToPublishDirectory>
</PropertyGroup>
<ItemGroup>
<!--<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="5.0.16" />-->
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.1" />
</ItemGroup>
</Project>
Then I delete Startup.cs and change Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add DB Contexts and Services here
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
More detail information, see this link.
You can create a new empty project to migrate from .net 5 to .net 6 and see if the problem still exists.I think this may be the problem caused by some of your configuration, maybe you can check whether your path is correct?
Chen's answer is the correct migration step.
I tried to reproduce your issue. When I comment Index page method in HomeController. And I face the same issue.
So you probably deleted your "Index" action in HomeController.
The answer appears to be "screw you, start over."
I've tried copying my project code to a new .net 6 project -- that is, copying all the views, controllers, and whatnot to the new project and updating the new Program.cs file accordingly -- and I still got the same error. I then tried converting a different .net 5 project to .net 6, and got the same error again. So apparently, converting just doesn't work.
So be it. I quit. I've got too much else to do to worry about this. Thanks to those who responded to this post for trying to help resolve it, anyway.

Login and Register doesnt work, which is rendered from _LoginPartial.cshtml using asp.net core 5.0

I am new to the ASP.Net Core 5.0 still learning.
As mentioned on the microsoft documentation I have used
but for some reason it doesnt work. The ConfirgurationServices in Start up file is up to date based on the document
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext.TestDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("Default")));
services.AddControllersWithViews();
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<TestDbContext>();
}
I have added
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
I have added the <partial name="_LoginPartial"/> on the layout page
Here I was expecting the template for the login and register to display when I run the project but nothing happens when I click the login or register.
how do I work around this?
_LoginPartial is using RazorPages, so in program.cs you have to call app.MapRazorPages(); after the MapControllerRoute

How to deploy ASP Core Web API VueJS site to IIS

I am new to VueJS and SPAs in general. I have created a new ASP Core site with a WebAPI controller for data and a VueJS front end. I am now trying to deploy this site to IIS and I am not sure how to do it correctly. I created a new application in IIS with an application pool set to "no-managed-code" and set the physical location to the VueJS app /dist folder. The site is loading, but I'm getting 404's for all of my service calls. I assume this is because the root of the site is set to the VueJS app folder instead of the root of the ASP Core folder. How do I set this up correctly to serve my app from myServer/mySite and also have my service endpoints as myServer/mySite/api/myController/myAction?
Scenario: Your dotnet core app has the API endpoints and you want to host the client site SPA on the same site. API calls will go through to the dotnet app and any other request will serve the index.html of the SPA.
.NET core supports this scenario with the methods from Microsoft.AspNetCore.SpaServices namespace like UseSpa()
Also note that in .NET 5 these extensions are moving to separate package Microsoft.AspNetCore.SpaServices.Extensions. It is available now but not well documented.
Your build SPA should go in ClientApp/dist in this example
e.g.
using Microsoft.AspNetCore.SpaServices;
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// In production, the SPA files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc();
// Must be near the end of the method because
// it will send any unhandled requests to index.html for SPA
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
// Development requests are send through to local node server
spa.UseProxyToSpaDevelopmentServer("http://localhost:8080/");
}
});
}
}

.NET Core rc2 WebAPI with index.html as default page

I have set up an empty WebAPI project with .NET Core rc2 and have it wired up with Angular2 rc1. Angular will handle everything view related and the WebAPI is the backend.
When I start the app by default it comes up with localhost:4578/api/values from the default API controller as startpage.
However, I want it to show index.html by default which is located in wwwroot and is hosting my Angular2 app.
In Startup.cs the Configure method looks like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
app.Run(ctx =>
{
ctx.Response.Redirect("/index.html");
return Task.FromResult(0);
});
}
app.UseStaticFiles and the app.Run lambda need to be in place for the manual redirect to index.html to work but it still comes up with /api/values as default start page.
I know that for debugging purposes I can change the start page easily but I want to change it such that when I host it it always serves index.html as start page.
How can I change this?
When creating a new empty WebAPI project, the launchsettings.json file points to api/values by default. To change it, go to the launchsettings.json file in your project:
and change the launchUrl value to: http://localhost:4578 (from http://localhost:4578/api/values).