Iam using asp.net core razor pages with Electron NET
in debug the Electron app its run with no errors whene i build it using electron cli
>electronize build /target win
and run the setup it installed and the app appears on task manager but no window
my code:in startup
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
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.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
if (HybridSupport.IsElectronActive)
{
CreateWindow();
}
}
private async void CreateWindow()
{
var window = await Electron.WindowManager.CreateWindowAsync();
window.OnClosed += () => {
Electron.App.Quit();
};
}
and in program:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseElectron(args);
webBuilder.UseStartup<Startup>();
});
its work properly when i use mvc project not razor pages
Related
I'm trying to implement a simple MVC controller in my Blazor WASM project, but I can't get the routing to work correctly. It always redirects me to the blazor "NotFound" component when I try to access it. I've spent alot of time trying configuring in my Startup.cs but I'm run out of ideas. I'm doing this on a boilerplate WASM project in .NET6. This is how my Startup.cs looks like:
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureApplicationServices();
services.ConfigurePersistenceServices(Configuration);
//services.AddMvc();
services.AddControllersWithViews();
services.AddRazorPages();
}
// 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();
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.UseMiddleware<ExceptionMiddleware>();
app.UseCors(config =>
config
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
//.WithExposedHeaders("header1", "header")
);
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
endpoints.MapFallbackToFile("index.html");
});
}
And this is my MVC controller:
[Route("[controller]/[action]")]
public class RoleManagerController : Controller
{
private readonly RoleManager<IdentityRole> _roleManager;
public RoleManagerController(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
public async Task<IActionResult> Index()
{
var roles = await _roleManager.Roles.ToListAsync();
return View(roles);
}
[HttpPost]
public async Task<IActionResult> AddRole(string roleName)
{
if (roleName != null)
{
await _roleManager.CreateAsync(new IdentityRole(roleName.Trim()));
}
return RedirectToAction("Index");
}
}
[Polite] There's must be some missing information in your question.
I've tested this using the Net6.0 out-of-the-box Blazor Hosted template and it works.
Here's my controller:
[ApiController]
[Route("[controller]/[action]")]
public class MyController : ControllerBase
{
public string Index()
{
return "hello. You called Index";
}
}
My (out-of-the-box) Program:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
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();
app.UseRouting();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
And the Postman result (using small letters):
I was implementing Swagger into my Blazor WebAssembly project and swagger does not seem to recognise any of my APIs? Can't seem to figure out the issue and was wondering if anyone knew why this might be occurring. Thanks in advance.
Installed Swashbuckle.AspNetCore in the Server project
My controllers do not use the traditional Route(["api/controller"]) but instead uses Route(["controller"]) which I do not think would cause this issue.
Furthermore all controller functions have been labelled with get/post/put e.g. HttpGet[(...)] ... etc
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
options.IdentityResources["openid"].UserClaims.Add("role");
options.ApiResources.Single().UserClaims.Add("role");
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role");
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddControllersWithViews();
services.AddRazorPages();
services.Configure<IdentityOptions>(options =>
options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
services.AddControllers().AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize);
services.AddSwaggerGen();
}
// This method gets called by the runtime. Use th is method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
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();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseSwagger();
app.UseSwaggerUI();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
}
The docs are a bit fragmented by the various options and versions. But the relevant line is:
Add endpoints if you're using endpoint-based routing.
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapSwagger(); // add this line
endpoints.MapFallbackToFile("index.html");
});
Check Swashbuckle.AspNetCore package version
I have a Web API based on dot net 6.
This Web API runs on Azure App Service. Azure App Service runs on Linux.
I'm using Open API (Swagger) for test and documentation.
I created 2 appsettings files. (Development and Stage.)
I'm adding ASPNETCORE_ENVIRONMENT variable to the configuration of Azure App Service like below. Functions work for two variables of ASPNETCORE_ENVIRONMENT (Development and Stage).
when I set the 'Stage' value to ASPNETCORE_ENVIRONMENT, the Swagger page is not working. It gives a 404 Not Found Error. But It works for Development.
Here is my startup code to swagger configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowAnyOrigin", builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }));
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "AllStore.Api", Version = "v1" });
var securitySchema = new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "bearer",
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
};
c.AddSecurityDefinition("Bearer", securitySchema);
var securityRequirement = new OpenApiSecurityRequirement
{
{ securitySchema, new[] { "Bearer" } }
};
c.AddSecurityRequirement(securityRequirement);
});
}
I really don't understand what is the problem? can anyone help me?
Changed the Configure method in the startup.cs like below
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AllStore.Api v1"));
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
instead of
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AllStore.Api v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Once after hosting the project both in local IIS and in server, I found that in server all the identity related pages throws 404 error, whereas in local IIS it works fine. All the other pages apart from Identity Pages are accessible. My StartUp class looks like this:
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSingleton<IFileProvider>(
new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));
var connectionString = this.Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(connectionString);
options.UseLazyLoadingProxies(true);
});
//services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddDefaultIdentity<XonetPlus_V3.Entities.Domain.User>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>().AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(#"c:\shared-auth-ticket-keys\"))
.SetApplicationName("SharedCookieApp");
services.ConfigureApplicationCookie(options => {
options.Cookie.Name = ".AspNet.SharedCookie";
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddTransient<IRepositoryWrapper, RepositoryWrapper>();
services.AddScoped<IEmailSender, EmailSender>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<User> userManager, RoleManager<IdentityRole> roleManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
IdentityDataInitializer.SeedData(userManager, roleManager);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=admindashboard}/{action=Index}/{id?}");
// endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute("queryParams", "{controller=admindashboard}/{action=Index}/{param}/{id}");
endpoints.MapControllerRoute("areas", "{area:exists}/{controller=admindashboard}/{action=Index}");
endpoints.MapRazorPages();
});
}
}
My asp.net core web application is not serving the ApiController route I have setup, however it used to work but I didn't change anything so idk why its not working now.
When I navigate to https://localhost:5001/api/Demo; it returns me to my sites homepage instead of running the action and displaying the data. the url in the address bar does change to …:5001/api/Demo, but does not display the data.
// controller
[ApiController]
[Route("api/[controller]")]
public class DemoController : ControllerBase
{
[HttpGet]
public string Index(string result)
{
return "test string";
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
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.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "api/{controller=Demo}/{action=Index}/{result?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
==============================================
UPDATE: add configure method from startup class