Skip to content

Instantly share code, notes, and snippets.

@vibs2006
Last active June 14, 2023 12:15
Show Gist options
  • Save vibs2006/e6455b80dbe762d53774c206b5c75e85 to your computer and use it in GitHub Desktop.
Save vibs2006/e6455b80dbe762d53774c206b5c75e85 to your computer and use it in GitHub Desktop.
SELF HOST API with Swagger Configuration for all .NET Versions
  1. ASP.NET >= v4.5.x versions covered (ASP.NET.Framework.4.5.Startup.cs)
  2. ASP.NET Core 6 (ASP.NET.Core.6.Startup.cs)
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting Padauk Web API Services");
try
{
var applicationName = "Padauk.API";
var builder = WebApplication.CreateBuilder(args);
var startup = new WebHostStartup(builder.Configuration);
startup.ConfigureServices(builder.Services);
var app = builder.Build();
startup.Configure(app, app.Environment);
if (app.Services.GetService(typeof(IHostEnvironment)) is IHostEnvironment env)
applicationName = env.ApplicationName;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
Console.Title = applicationName;
Console.WriteLine("Running...");
app.Run();
}
catch (Exception Ex)
{
Console.WriteLine("Unable to start");
Console.WriteLine(Ex.Message);
Console.WriteLine(Ex.StackTrace);
while (Ex.InnerException != null)
{
Ex = Ex.InnerException;
Console.WriteLine(Ex.Message);
Console.WriteLine(Ex.StackTrace);
}
}
}
}
public class WebHostStartup
{
public IConfiguration Configuration { get; }
private readonly string _secretKey;
private readonly string _connectionString;
public WebHostStartup(IConfiguration configuration)
{
_secretKey = configuration.GetValue<string>("ApiSettings:Secret");
_connectionString = configuration.GetConnectionString("DefaultConnection");
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
services
.AddTransient<IHttpClientService, HttpClientFactoryServiceImplementation>();
services.AddControllers().AddJsonOptions(jsonOptions => {
jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null;
});
services.AddScoped<IDbConnection>(rep =>
new SqlConnection(_connectionString));
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x => {
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_secretKey)),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Bearer Authorization header\r\n\r\n" +
"Enter 'Bearer' [space] and then your token in text input below\r\n\r\n" +
"Example \"Bearer 56325hsdf \"",
Name = "Authorization",
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header
},
new List<string>()
}
});
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1.0",
Title = "PH Pro API",
Description = "Miroservice to Manage PH Pro",
TermsOfService = new Uri("http://parcelhero.com")
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(options => {
options.SwaggerEndpoint("/swagger/v1/swagger.json", "PH Pro API");
});
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
}
//Startup.cs
/*
Nuget Packages Required
Microsoft.AspNet.Cors
Microsoft.AspNet.WebApi.Client
Microsoft.AspNet.WebApi.Core
Microsoft.AspNet.WebApi.Cors
Microsoft.AspNet.WebApi.Owin
Microsoft.AspNet.WebApi.OwinSelfHost
Microsoft.Owin
Microsoft.Owin.FileSystems
Microsoft.Owin.Host.HttpListener
Microsoft.Owin.Hosting
Microsoft.Owin.StaticFiles
Newtonsoft.Json
Owin
Swashbuckle.Core
*/
using System;
using System.Configuration;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;
using Microsoft.Owin;
using Microsoft.Owin.FileSystems;
//using Microsoft.Owin.Security.OAuth;
using Microsoft.Owin.StaticFiles;
using Owin;
using Swashbuckle.Application;
[assembly: OwinStartup(typeof(SelfHostingWIndowsServiceAPI.Startup))]
namespace SelfHostingWIndowsServiceAPI
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// ConfigureOAuth(app);
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
// Enable attribute based routing
// http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional, controller = "Home", action = "Index" }
);
//config.Routes.MapHttpRoute(
// name: "DefaultApi2",
// routeTemplate: "{controller}/{action}/{id}",
// defaults: new { id = RouteParameter.Optional, controller = "Home", action = "Index" }
//);
//config.Filters.Add(new AddCustomHeaderFilter());
app.UseWebApi(config);
var physicalFileSystem = new PhysicalFileSystem(@"./www");
var options = new FileServerOptions
{
EnableDefaultFiles = true,
FileSystem = physicalFileSystem
};
options.StaticFileOptions.FileSystem = physicalFileSystem;
options.StaticFileOptions.ServeUnknownFileTypes = true;
options.DefaultFilesOptions.DefaultFileNames = new[]
{
"index.html"
};
app.UseFileServer(options);
config.EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API")) .EnableSwaggerUi();
}
//public void ConfigureOAuth(IAppBuilder app)
//{
// OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
// {
// AllowInsecureHttp = true,
// TokenEndpointPath = new PathString("/token"),
// AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
// Provider = new SimpleAuthorizationServerProvider()
// };
// // Token Generation
// app.UseOAuthAuthorizationServer(OAuthServerOptions);
// app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
//}
}
//public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
//{
// public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
// {
// context.Validated();
// }
// public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
// {
// var configUsername = ConfigurationManager.AppSettings.Get("UserName").Trim();
// var configPassword = ConfigurationManager.AppSettings.Get("Password").Trim();
// if (context.OwinContext.Response.Headers["Access-Control-Allow-Origin"] == null)
// {
// context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
// }
// if (string.IsNullOrWhiteSpace(context.UserName) || string.IsNullOrWhiteSpace(context.Password))
// {
// context.SetError("invalid_grant", "The user name or password is empty.");
// return;
// }
// else if (context.UserName == configUsername && context.Password == configPassword)
// {
// var identity = new ClaimsIdentity(context.Options.AuthenticationType);
// identity.AddClaim(new Claim("sub", context.UserName));
// identity.AddClaim(new Claim("role", "user"));
// context.Validated(identity);
// }
// else
// {
// context.SetError("invalid_grant", "The user name or password is incorrect");
// return;
// }
// }
//}
}
//Program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
IDisposable _server = null;
int currentPortNumber = 4500;
//public string baseAddress = "http://127.0.0.1:8080/";
}
_server = WebApp.Start<Startup>(new StartOptions
{
Port = currentPortNumber
});
//_server = WebApp.Start<Startup>(url: baseAddress);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment