I have a Blazor WebAssembly app which is hosted by a .net Core app. I've been upgrading it from .net 6.0 and was using a Startup class to initialize the server app
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args)
.Build()
.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureHostConfiguration(conf =>
{
conf.AddJsonFile($"appsettings.{Environment.MachineName}.json", optional: true, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment environment)
{
Configuration = configuration;
WebHostEnvironment = environment;
}
public IConfiguration Configuration { get; }
public IWebHostEnvironment WebHostEnvironment { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
/*Other services registered here*/
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Configure the HTTP request pipeline.
if (env.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
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.UseStaticFiles();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
}
Now when I run this app, I can't get hot reloading of Blazor or CSS at all.
What I've found is that if I use the newer pattern implementing WebApplication.CreateBuilder, hot reloading works.
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
ConfigureServices(builder.Services, builder.Configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
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.UseBlazorFrameworkFiles();
app.UseStaticFiles();
var imagesPhysicalPath = app.Configuration.GetSection("ImagesDirectoryPath").Get<string>(); ;
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
RequestPath = "/product-images",
FileProvider = new PhysicalFileProvider(imagesPhysicalPath)
});
app.UseRouting();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
}
I marginally prefer the former version as it allows me to customise the Configuration mechanism.
Can anyone tell me what I'm missing in the original setup that might have broken the hot reload process?
Related
I'm using DotNet 5.0, and even though I register HttpContextAccessor in the Startup.ConfigureServices whenever I try to reach it inside the code, IHttpContextAccessor.HttpContext is always null.
This is my Startup.cs file's ConfigureServices Method
public void ConfigureServices(IServiceCollection services)
{
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
this.Configuration = new ConfigurationBuilder().SetBasePath(System.IO.Directory.GetCurrentDirectory()).AddJsonFile($"appsettings.{environmentName}.json").Build();
services.AddControllers();
services.AddSimpleInjector(container, options =>
{
options.AddAspNetCore();
});
services.AddHttpContextAccessor();
}
And this is the Configure method of the same file:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSimpleInjector(container);
container.Verify();
}
And also I'm using hangfire, but whenever a job gets triggered I cannot reach HttpContextAccessor through dependency injection. It is always null.
For example this is one of my business layer files:
public class FooService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public FooService(IHttpContextAccessor httpContextAcessor)
{
_httpContextAccessor = httpContextAccessor;
}
public DoSomething()
{
var tryoutVar = _httpContextAccessor.HttpContext;
}
}
The tryoutVar variable is set to null, always.
Why is this happening?
I want to read in an environment specific appsettings.json based on ASPNETCORE_ENVIRONMENT.
The example Microsoft gives for startup.cs is as follows for core 3.0:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
In previous versions, code I have seen to add an environmental specific appsettings.json is:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
How would I change the standard Microsoft example to include this?
"environment specific appsettings.json based on ASPNETCORE_ENVIRONMENT" is already done by convention by the call CreateDefaultBuilder() in your Program.cs file.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.0#default-configuration
So you do not need to do anything else. Just set up your ASPNETCORE_ENVIRONMENT value
I am using Azure AD for authentication in my ASP.net core app. I can retrieve a token from Azure using postman but when I go to make a request I get the following errror:
"Bearer error="invalid_token", error_description="The signature is invalid""
Setup.cs
namespace CoreDesk.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "https://sts.windows.net/7d63a3a5-79de-44c2-b5a3-ec21f4d24329/";
options.Audience = "00000003-0000-0000-c000-000000000000";
options.TokenValidationParameters.ValidateLifetime = true;
options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// 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.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader());
app.UseAuthentication();
app.UseMvc();
}
}
}
I tried to add swagger to an existing api and after failing alot, i decided to create a new solution, create a new asp.net core 2.2 api and added swagger as per
https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.2&tabs=visual-studio
The other posts regarding this issue seem all to indicate a situation where there are multiple httpverbs or none, which is not the case with the default valuescontroller. It gives me the error
Failed to load API Definition.
Fetch error, Service unavailable /swagger/v1/swagger.json
The actual json file at api/swagger/v1/swagger.json actually renders correctly
My startup class is
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerGen(c =>{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseMvc();
}
}
Im using Swachbuckle.AspNetCore v 4.01.
String SwaggerEndpoint = "/swagger/v1/swagger.json";
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
SwaggerEndpoint = "/andi/swagger/v1/swagger.json";
}
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint(SwaggerEndpoint, "My API");
//options.RoutePrefix = string.Empty;
});
Working on a dot net web API hosted on my local IIS and each time i try to call the API from a mobile application i'm developing, i get Internal server error(500). After several hours of debugging, i copied that is being sent to the API from ripple emulator i'm using on chrome and tried to do a get action manually. What i noticed though is after specifying localhost url and every necessary thing, the browser tries to search for it though google rather than use address specified .
> public class Program
> {
> public static void Main(string[] args)
> {
> CreateWebHostBuilder(args).Build().Run();
> }
>
> public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
> WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
program file above and start up file below
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddCors(options => options.AddPolicy("AllowCors", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader()));
services.Configure<IISOptions>(options =>
{
options.ForwardClientCertificate = false;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseCors("AllowCors");
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseCookiePolicy();
//app.UseMiddleware<RequestResponseLoggingMiddleware>();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Account}/{action=Login}/{id?}");
});
}