How to load a view by default instead of Swagger UI? - swagger

I'm working on a .NET 6 web api and I've configured the Program.cs to use Swagger UI when in development mode. How can I change this so that I still have access to Swagger UI but by default load the default view?
For example, when I run my project, it loads https://localhost:7004/swagger/index.html instead I want to load https://localhost:7004 but still have access to https://localhost:7004/swagger/index.html
Current Program.cs:
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.MapControllerRoute(
name: "default",
pattern: "{controller=ControllerName}/{action=Index}/{id?}");

Open your project's priperties (screenshot below -)
Under the 'Debug'section, click on 'Open debug launch profiles UI'. This should open the UI shown below -
Remove the text 'swagger', leave it blank, restart your application. This should navigate to -
Note that you can still enter full path to swagger link to navigate to it -

open launchsettings.json and remove launch url
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:41869",
"sslPort": 44362
}
},
"profiles": {
"WebApplication2": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger", // remove this
"applicationUrl": "https://localhost:7189;http://localhost:5189",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger", // remove this
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

Related

How to Auto update using onclick in electronjs

I am developing small application in electronJS and implemented auto update function working fine with log file. but I need with custom window option see attached image could you please update my code and attached my code below. What I am missing refer more references but could not solve this issue.
enter image description here
main.js
`
main.js
// Modules to control application life and create native browser window
const {app, BrowserWindow,ipcMain, dialog } = require('electron')
const path = require('path')
const { autoUpdater }=require('electron-updater')
const log = require('electron-log');
log.transports.file.resolvePath = () => path.join('F:/electronjs/test/electron-quick-start', '/logs/m.log');
log.info("Application version" + app.getVersion())
log.info('Hello, log');
log.warn('loading');
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
// updateInterval = setInterval(() => autoUpdater.checkForUpdates());
autoUpdater.checkForUpdatesAndNotify();
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
autoUpdater.on('update-available',() => {
log.info('update-available')
})
autoUpdater.on('checking-for-update',() => {
log.info('checking-for-update')
})
autoUpdater.on('download-progress',(progressTrack) => {
log.info('download-progress')
log.info(progressTrack)
})
autoUpdater.on('update-downloaded',() => {
log.info('update-downloaded')
})
Package.json
`
{
"name": "electron-quick-start",
"version": "8.0.9",
"description": "A minimal Electron application",
"main": "main.js",
"scripts": {
"start": "electron .",
"pack": "electron-builder",
"package": "electron-builder -p always"
},
"build": {
"publish": [
{
"provider": "github",
"owner": "vansiva",
"repo": "electron"
}
]
},
"keywords": [
"Electron",
"quick",
"start",
"tutorial",
"demo"
],
"author": "GitHub",
"license": "CC0-1.0",
"devDependencies": {
"electron": "^21.2.3",
"electron-builder": "^23.6.0"
},
"dependencies": {
"electron-log": "^4.4.8",
"electron-updater": "^5.3.0"
}
}`
I need auto update with custom popup box

I get 404 error after configuring AspNetCoreRateLimit library in my code

When I remove the rate related codes, the app works fine. If I write these codes, I get 404 error.
If await webHost.RunAsync(); , await IpPolicy.SeedAsync(); If I remove the await keyword in the , I get the error localhost refused to connect. How can I solve this problem?
Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext(builder);
builder.Services.AddControllersWithViews();
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
builder.Services.AddFluentValidationAutoValidation().AddFluentValidationClientsideAdapters();
builder.Services.AddMapster();
builder.Services.AddIdentity();
builder.Services.AddCookieConfiguration();
builder.Services.AddOptions();
builder.Services.AddMemoryCache();
builder.Services.Configure<IpRateLimitOptions>(builder.Configuration.GetSection("IpRateLimiting"));
builder.Services.Configure<IpRateLimitPolicies>(builder.Configuration.GetSection("IpRateLimitPolicies"));
builder.Services.AddInMemoryRateLimiting();
builder.Services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
builder.Services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
using IHost webHost = builder.Build();
using (var scope = webHost.Services.CreateScope())
{
IIpPolicyStore IpPolicy = scope.ServiceProvider.GetRequiredService<IIpPolicyStore>();
await IpPolicy.SeedAsync();
}
await webHost.RunAsync();
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.UseIpRateLimiting();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
RoleSeed.Seed(app);
app.Run();
appsettings.json
{
"ConnectionStrings": { "SqlCon": "" },
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"IpRateLimiting": {
"EnableEndpointRateLimiting": true,
"StackBlockedRequests": false,
"HttpStatusCode": 429,
//"IpWhitelist": [ "127.0.0.12" ],
//"EndpointWhitelist": [ "*:/api/customers" ],
"GeneralRules": [
{
"Endpoint": "*",
"Period": "10 s",
"Limit": 20
}
]
},
"IpRateLimitPolicies": {
"IpRules": [
{
"Ip": "*",
"Rules": [
{
"Endpoint": "*",
"Period": "10m",
"Limit": 150
}
]
}
]
}
}
i changed the service order and then i got this error how can i solve it?

How to deploy aspnet core app on linx docker container without getting 404 error

I've got a ASPNET Core 5.0 web api app running successfully locally on Windows but failing when deployed to linux docker container which is hosted on linux server. Page won't load when navigating to http://internal.apps.talquinelectric.com/is/api. I'm getting a 404 error.
launchSettings.json
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:80",
"sslPort": 80
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"FixBatchAPI": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "http://internal.apps.talquinelectric.com/is/api",
"applicationUrl": "http://internal.apps.talquinelectric.com/is/api",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
}
}
}
Startup.cs
// 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.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "FixBatchAPI v1"));
}
//app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Dockerfile
# syntax=docker/dockerfile:1
FROM mcr.microsoft.com/dotnet/aspnet:5.0
COPY FixBatchAPI/net50/ App/
WORKDIR /App
ENTRYPOINT ["dotnet", "FixBatchAPI.dll"]
docker-compose.yml
version: "3"
services:
fixbatch-api:
image: "fixbatch-api-build:latest"
container_name: "fixbatch-api"
networks:
- traefix_proxy
labels:
- "traefik.enable=true"
- "traefik.docker.network=traefik_proxy"
- "traefik.http.routers.fixbatch-api.entrypoint=https"
- "traefik.http.routers.fixbatch-api.tls=true"
- "traefik.http.routers.fixbatch-api.rule=Host(`internal.apps.talquinelectric.com`) && PathPrefix(`/is/api`)"
- "traefik.http.services.fixbatch-api-service.loadbalancer.server.port=80"
- "traefik.http.middlewares.fixbatch-api-middlewares.chain.middlewares=fixbatch-api-strip"
- "traefik.http.middlewares.fixbatch-api-strip.stripprefix.prefixes=/is/api"
- "traefik.http.routers.fixbatch-api-http.entrypoint=http"
- "traefik.http.routers.fixbatch-api-http.rule=Host(`internal.apps.talquinelectric.com`) && PathPrefix(`/is/api`)"
- "traefik.http.middlewares.fixbatch-api-redirect-https.redirectscheme.scheme=https"
- "traefik.http.routers.fixbatch-api-http.middlewares=fixbatch-api-redirect-https"
- "traefik.http.middlewares.cors.headers.accesscontrolallowmethods=GET,OPTIONS,PUT"
- "traefik.http.middlewares.cors.headers.accesscontrolalloworigin=*"
- "traefik.http.middlewares.cors.headers.addvaryheader=true"
networks:
traefik_proxy:
external: true
default:
external: false
Result of docker-compose logs:
What I get when viewing in browser:
Add code like below, you can open swaggerui page.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "FixBatchAPI v1"));
}
// default, no below code
else {
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "FixBatchAPI v1"));
}

White screen and no error in Angular electron app not loading index.html after building with electron builder

I have an angular electron app that works perfectly fine ( dev environment ) before bundling it with electron-builder. After bundling, install and opening it, a got a white screen without error !!
Here's the package.json file of my project
{
"name": "groceryee",
"productName": "Groceryee",
"authors": "seifou eddine",
"description": "groceryee",
"version": "9.3.1",
"scripts": {
"ng": "ng",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"start": "concurrently \"ng serve\" \"npm run electron\"",
"electron": "electron ./src/electron.dev",
"build-installer": "electron-builder"
},
"build": {
"appId": "com.groceryee.webconcepter",
"copyright": "Copyright © 2021 groceryee",
"asar":false,
"win": {
"target": [
"nsis"
],
"requestedExecutionLevel": "requireAdministrator"
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"uninstallDisplayName": "groceryee",
"license": "license.txt"
},
"extraMetadata": {
"main": "src/electron.prod.js"
}
}
}
Here's my electron.prod.js file of my project
const { app, BrowserWindow } = require('electron');
const path = require('path');
const url = require('url');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;
const createWindow = () => {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
icon: path.join(__dirname, 'favicon.ico'),
});
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
win.webContents.openDevTools();
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow();
}
});
I'm really confused! i believe that all my code is correct, possible that I forgot something
Any ideas, please !!
Try to delete "requestedExecutionLevel": "requireAdministrator" option in package.json
Or change requestedExecutionLevel value to "asInvoker"
It works for me

registering custom protocol at installation process in electron app

Hi I am new to electron and was wondering how i can register a custom protocol for the app at the time of installation process of the app.
I am using electron-builder for building the app. Here is the build build code
"build": {
"appId": "com.test.testapp",
"productName": "testapp",
"asar": true,
"protocols": [{
"name": "testapp",
"schemes": [ "testapp" ]
}],
"nsis": {
"oneClick": false,
"perMachine": true,
"allowToChangeInstallationDirectory": true,
"runAfterFinish": false,
"createDesktopShortcut": true
},
"squirrelWindows": {
"msi": true
},
"directories": {
"output": "distribution"
}
I know that by adding the below line registers the custom protocol
app.setAsDefaultProtocolClient("testapp");
but it only does if i run the app at least the first time.
Which i don't want there is no guarantee that the user will launch the app after installation.
So is there a way that i can register the custom protocol in the installation process using electron-builder
I'm still new to Electron and electron-builder but solved this problem for NSIS-target already. First of all I should note that app.setAsDefaultProtocolClient used to handle custom protocols inside the application as far as I do understand. You need to register this custom protocol using electron-builder itself.
Secondly I need to choose between NSIS and squirrelWindows. NSIS is the preferable as long I understand because Squirrel is less supported and has some problems. Again I'm not an expert but I read something about it. So squirrelWindows section is redundant. You don't specify win.target and it is "nsis" by default.
There is a problem with the custom protocol registration for NSIS target. You can read more here: Protocol (scheme) for windows but there is a workaround. You need to create a file named installer.nsh in your build folder with such a content:
!macro customInstall
DetailPrint "Register evehq-ng URI Handler"
DeleteRegKey HKCR "evehq-ng"
WriteRegStr HKCR "evehq-ng" "" "URL:evehq-ng"
WriteRegStr HKCR "evehq-ng" "EveHQ NG SSO authentication Protocol" ""
WriteRegStr HKCR "evehq-ng\DefaultIcon" "" "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
WriteRegStr HKCR "evehq-ng\shell" "" ""
WriteRegStr HKCR "evehq-ng\shell\Open" "" ""
WriteRegStr HKCR "evehq-ng\shell\Open\command" "" "$INSTDIR\${APP_EXECUTABLE_FILENAME} %1"
!macroend
Replace evehq-ng with your protocol string and EveHQ NG SSO authentication Protocol with your protocol description.
After that you have to set nsis.perMachine to true.
I haven't yet solved this problem for Linux but work in this direction. You can see my code in my proof of concepts project here: EveHQ-NG proof of concepts application.
If you will solve this problem for Linux and MacOS write me a message somehow here or on GitHub.
Hope it helps.
Since you are using electron-builder you can do the following:
"build": {
... other top level electron-builder keys ...
"protocols": [
{
"name": "Custom Protocol Name",
"schemes": [
"customProtocol"
]
}
]
}
In case you wanted to handle customProtocol://some-link with your application.
More details:
https://www.electron.build/configuration/configuration
(Search for protocols; as of now, the documentaion is a little mis-formatted. It's supposed to be the same top-level key as the fileAssociations key above it.)
custom protocol is still opening only after opening the electron application. And I also added installer.nsh inside build folder. I don't know what's the problem.
package.json
{
"name": "electron-project",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron .",
"pack": "build --dir",
"dist": "build"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^3.0.8",
"electron-builder": "^20.38.5"
},
"dependencies": {
"axios": "^0.18.0"
},
"build": {
"win": {
"target": "nsis"
},
"nsis": {
"oneClick" : false ,
"allowToChangeInstallationDirectory": true,
"include" : "dist/installer.nsh" ,
"perMachine" : true
},
"protocols": [{
"name": "electron-deep-linking",
"schemes": [
"test"
]
}],
"mac": {
"category": "public.app-category.Reference"
}
}
}
main.js
const { app, BrowserWindow } = require('electron')
const path = require('path')
const url = require('url')
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({ width: 800, height: 600 })
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.setAsDefaultProtocolClient('test')
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
Electron providing a very simple way to registering custom protocol URL in client machine(Windows, Mac)
so this way we can register and remove our own custom protocol in machine
const {app} = require('electron')
app.on('ready', onReady)
function onReady() {
.... // write other code
if(!app.isDefaultProtocolClient('quickstart')) {
app.setAsDefaultProtocolClient("quickstart", 'C:\\Users\\karthi\\electron-quick-start\\electron-quick-start-win32-x64\\electron-quick-start.exe');
}
}
this code will register the custom protocol in machine, then you can open your app using browser like quickstart://params
for removing the custom protocol in machine
app.removeAsDefaultProtocolClient("quickstart", 'C:\\Users\\karthi\\electron-quick-start\\electron-quick-start-win32-x64\\electron-quick-start.exe');
here i used electron quick start app and i used electron-packager npm for building my app
For more information custom protocol electron-protocol

Resources