API Project - APS.
NET Core Web API
Repository Project - Class Library
DataAccess Project - Class Library
[
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
]
DEPENDENCY ỊNECTION
appsettings.json:
"ConnectionStrings": {
"MyConnectionString": "Data Source=(local);Initial Catalog=assignment_prn_231;User
ID=sa;Password=12345;Trusted_Connection=True;Trust Server Certificate=True"
},
"JWT": {
"SecretKey": "ThisIsTheSecretKey0987654321"
}
dotnet ef dbcontext scaffold "Data Source=(local);Initial Catalog=assignment_prn_231;User
ID=sa;Password=12345;Trusted_Connection=True;Trust Server Certificate=True"
"Microsoft.EntityFrameworkCore.SqlServer" --output-dir "DataAccess"
context:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(GetConnectionString());
}
}
private string GetConnectionString()
{
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.Build();
var strConn = config["ConnectionStrings:MyConnectionString"];
return strConn;
}
PROGRAM.CS
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Assignment_PRN", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Please Enter The Token To Authenticate The Role",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(builder.Configuration["JWT:SecretKey"])
)
};
});
builder.Services.AddSession();
// DI
builder.Services.AddScoped<IBranchAccountDAO, BranchAccountDAO>();
builder.Services.AddScoped<ISilverJewelryDAO, SilverJewelryDAO>();
builder.Services.AddScoped<ICategoryDAO, CategoryDAO>();
builder.Services.AddDbContext<SilverJewelry2024DBContext>();
builder.Services.AddScoped<IBranchAccountRepository, BranchAccountRepository>();
builder.Services.AddScoped<ISilverJewelryRepository, SilverJewelryRepository>();
builder.Services.AddScoped<ICategoryRepository, CategoryRepository>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
//builder.Services.AddSwaggerGen();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
//app.UseSwagger();
//app.UseSwaggerUI();
app.UseStaticFiles();
}
app.UseHttpsRedirection();
app.UseCors("AllowSpecificOrigin");
app.UseRouting();
// Authentication
app.UseSession();
app.UseMiddleware<JwtTokenMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Assignment_PRN"));
app.MapControllers();
app.UseStaticFiles();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "account",
pattern: "{controller=BranchAccounts}/{action=Login}/{id?}");
});
app.Run();
}
MIDDLE WARE
public class JwtTokenMiddleware
{
private readonly RequestDelegate _next;
public JwtTokenMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var jwtToken = context.Session.GetString("JwtToken");
if (!string.IsNullOrEmpty(jwtToken))
{
context.Request.Headers.Add("Authorization", "Bearer " + jwtToken);
}
await _next(context);
}
}