SlideShare a Scribd company logo
ASP.NET Core
binary-studio.com
Contents
1. Intro
2. Startup
3. Middleware
4. Logging
5. Static files
6. Routing
7. Authentication
8. Configuration
Intro
What is ASP.NET Core?
leaner and modular architecture
tighter security
reduced servicing
improved performance
pay-for-what-you-use model.
Why is ASP.NET Core?
Integration of modern client-side frameworks and development workflows
A cloud-ready environment-based configuration system
Built-in dependency injection
New light-weight and modular HTTP request pipeline (No System.Web.dll
Ability to host on IIS or self-host in your own process
Built on .NET Core, which supports true side-by-side app versioning
Ships entirely as NuGet packages
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel() //
.UseServer("Microsoft.AspNet.Server.Kestrel")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
Startup
Configure - how the ASP.NET application will respond to individual HTTP
requests.
ConfigureServices - method for configuring services that are used by your
application.
Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (!env.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
Middleware
Pipeline with IApplicationBuilder
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseExceptionHandler("/Home/Error"); // Middleware 1
app.UseStaticFiles(); // Middleware 2
app.UseIdentity(); // Middleware 3
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
}); // Middleware 4
}
Custom pipeline
public void ConfigureLogInline(IApplicationBuilder app, ILoggerFactory loggerfactory)
{
loggerfactory.AddConsole(minLevel: LogLevel.Information);
var logger = loggerfactory.CreateLogger(_environment);
app.Use(async (context, next) =>
{
logger.LogInformation("Handling request.");
await next.Invoke(); // Comment it to terminate the
pipeline
logger.LogInformation("Finished handling request.");
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from " + _environment);
});
}
Logging
Logging
Interfaces:
ILoggerFactory
ILogger
Extension methods:
AddConsole
AddDebug
AddTraceSource
Simple logging
[Route("api/[controller]")]
public class TodoController : Controller
{
private readonly ITodoRepository _todoRepository;
private readonly ILogger<TodoController> _logger;
public TodoController(ITodoRepository todoRepository,
ILogger<TodoController> logger)
{
_todoRepository = todoRepository;
_logger = logger;
}
[HttpGet]
public IEnumerable<TodoItem> GetAll()
{
_logger.LogInformation(LoggingEvents.LIST_ITEMS, "Listing all items");
return _todoRepository.GetAll();
}
}
Thirdparty Providers
elmah.io - provider for the elmah.io service
Loggr - provider for the Loggr service
NLog - provider for the NLog library
Serilog - provider for the Serilog library
your own
Static Files
Set directory to content:
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
Set static files to pipeline:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(),
@"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles")
});
}
Content type mapping
public void Configure(IApplicationBuilder app)
{
// Set up custom content types -associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4");
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwrootimages")),
RequestPath = new PathString("/MyImages"),
ContentTypeProvider = provider
});
}
Routing
URL Matching
Request
Route 1
Route 2
Route N
RouterMiddleware
.RouteAsync()
Handle()
Next()
Mapping
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "us_english_products",
template: "en-US/Products/{id}",
defaults: new { controller = "Products", action = "Details" },
constraints: new { id = new IntRouteConstraint() },
dataTokens: new { locale = "en-US" });
Routing Middleware
public void ConfigureServices(
IServiceCollection services)
{
services.AddRouting();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var trackPackageRouteHandler = new RouteHandler(context =>
{
var routeValues = context.GetRouteData().Values;
return context.Response.WriteAsync(
$"Hello! Route values: {string.Join(", ", routeValues)}");
});
var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);
routeBuilder.MapRoute(
"Track Package Route",
"package/{operation:regex(^track|create|detonate$)}/{id:int}");
routeBuilder.MapGet("hello/{name}", context =>
{
var name = context.GetRouteValue("name");
return context.Response.WriteAsync($"Hi, {name}!");
});
var routes = routeBuilder.Build();
app.UseRouter(routes);
RouteBuilder methods
MapRoute
MapGet
MapPost
MapPut
MapDelete
MapVerb
Authentication
Identity
// Authentication should be set to Individual User Accounts
// ConfigureServices
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Configure
app.UserIdentity();
// Manage users
UserManager<ApplicationUser> _usermanager;
// Manage sign in/sign out
SignInManage<ApplicationUser> _signinmanager;
Facebook, Twitter, Google Providers
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"]
});
// Other providers use similar approach
Other Features
Two-factor authentication with SMS
Supporting Third Party Clients using OAuth 2.0
Azure Active Directory
Securing ASP.NET Core apps with IdentityServer4
Configuration
var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory());
builder.AddJsonFile("appsettings.json");
builder.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
builder.AddCommandLine(args);
var connectionStringConfig = builder.Build();
var str = connectionStringConfig.GetConnectionString("DefaultConnection")
IOptions
// ConfigureServices
services.AddOptions();
services.Configure<MyOptions>(Configuration);
// Configure MyOptions using code
services.Configure<MyOptions>(myOptions =>
{
myOptions.Option1 = "value1_from_action";
myOptions.Option2 = connectionStringConfig.GetConnectionString("DefaultConnection");
});
public class HomeController : Controller
{
private readonly IOptions<MyOptions> _optionsAccessor;
public HomeController(IOptions<MyOptions> optionsAccessor)
{
_optionsAccessor = optionsAccessor;
}
// GET: /<controller>/
public IActionResult Index() => View(_optionsAccessor.Value);
}
public class MyOptions
{
public string Option1 { get; set;
}
public string Option2 { get; set;
}
}
Error Handling
Exception Handling Page
// Configure
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
Status Code Pages
// Configure
app.UseStatusCodePages();
app.UseStatusCodePages(context =>
context.HttpContext.Response.SendAsync("Handler, status code: " +
context.HttpContext.Response.StatusCode, "text/plain"));
app.UseStatusCodePages("text/plain", "Response, status code: {0}");
app.UseStatusCodePagesWithRedirects("~/errors/{0}");
app.UseStatusCodePagesWithReExecute("/errors/{0}");
ASP.NET MVC Handling
Exception filters
Model validation
Swagger
Swagger is a machine readable representation of a RESTful API
Swashbuckle is an open source project for generating Swagger documents for
Web APIs
Set Up
// Install package
Install-Package Swashbuckle -Pre
Add Swashbuckle to project.json: "Swashbuckle": "6.0.0-beta902"
// Configure
// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUi();
// ConfigureServices
// Inject an implementation of ISwaggerProvider with defaulted settings applied
services.AddSwaggerGen();
Ad

Recommended

Data Binding
Data Binding
LAY Leangsros
 
Servlets intro
Servlets intro
vantinhkhuc
 
Android - Saving data
Android - Saving data
Matteo Bonifazi
 
Backendless apps
Backendless apps
Matteo Bonifazi
 
Client Server Communication on iOS
Client Server Communication on iOS
Make School
 
Advanced #2 networking
Advanced #2 networking
Vitali Pekelis
 
10 sharing files and data in windows phone 8
10 sharing files and data in windows phone 8
WindowsPhoneRocks
 
State management in ASP.NET
State management in ASP.NET
Om Vikram Thapa
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
Michele Capra
 
Spring java config
Spring java config
Sukjin Yun
 
Url programming
Url programming
vantinhkhuc
 
Codemotion appengine
Codemotion appengine
Ignacio Coloma
 
Simple blog wall creation on Java
Simple blog wall creation on Java
Max Titov
 
Core Data with Swift 3.0
Core Data with Swift 3.0
Korhan Bircan
 
Multithreading on iOS
Multithreading on iOS
Make School
 
Spring4 whats up doc?
Spring4 whats up doc?
David Gómez García
 
Programming IoT Gateways with macchina.io
Programming IoT Gateways with macchina.io
Günter Obiltschnig
 
Spring 4 - A&BP CC
Spring 4 - A&BP CC
JWORKS powered by Ordina
 
Modern Android app library stack
Modern Android app library stack
Tomáš Kypta
 
Intro to Parse
Intro to Parse
Tushar Acharya
 
What's new in iOS 7
What's new in iOS 7
barcelonaio
 
What's Parse
What's Parse
Tsutomu Ogasawara
 
RESTfull with RestKit
RESTfull with RestKit
Taras Kalapun
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出
Ymow Wu
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
Michele Capra
 
Building Android apps with Parse
Building Android apps with Parse
DroidConTLV
 
How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...
Priyobroto Ghosh (Mule ESB Certified)
 
Birhanu distributive assignment
Birhanu distributive assignment
university
 
Introduction to .NET with C# @ university of wayamba
Introduction to .NET with C# @ university of wayamba
Prageeth Sandakalum
 
ASP .NET Core MVC
ASP .NET Core MVC
Vinicius Mussak
 

More Related Content

What's hot (20)

Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
Michele Capra
 
Spring java config
Spring java config
Sukjin Yun
 
Url programming
Url programming
vantinhkhuc
 
Codemotion appengine
Codemotion appengine
Ignacio Coloma
 
Simple blog wall creation on Java
Simple blog wall creation on Java
Max Titov
 
Core Data with Swift 3.0
Core Data with Swift 3.0
Korhan Bircan
 
Multithreading on iOS
Multithreading on iOS
Make School
 
Spring4 whats up doc?
Spring4 whats up doc?
David Gómez García
 
Programming IoT Gateways with macchina.io
Programming IoT Gateways with macchina.io
Günter Obiltschnig
 
Spring 4 - A&BP CC
Spring 4 - A&BP CC
JWORKS powered by Ordina
 
Modern Android app library stack
Modern Android app library stack
Tomáš Kypta
 
Intro to Parse
Intro to Parse
Tushar Acharya
 
What's new in iOS 7
What's new in iOS 7
barcelonaio
 
What's Parse
What's Parse
Tsutomu Ogasawara
 
RESTfull with RestKit
RESTfull with RestKit
Taras Kalapun
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出
Ymow Wu
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
Michele Capra
 
Building Android apps with Parse
Building Android apps with Parse
DroidConTLV
 
How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...
Priyobroto Ghosh (Mule ESB Certified)
 
Birhanu distributive assignment
Birhanu distributive assignment
university
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
Michele Capra
 
Spring java config
Spring java config
Sukjin Yun
 
Simple blog wall creation on Java
Simple blog wall creation on Java
Max Titov
 
Core Data with Swift 3.0
Core Data with Swift 3.0
Korhan Bircan
 
Multithreading on iOS
Multithreading on iOS
Make School
 
Programming IoT Gateways with macchina.io
Programming IoT Gateways with macchina.io
Günter Obiltschnig
 
Modern Android app library stack
Modern Android app library stack
Tomáš Kypta
 
What's new in iOS 7
What's new in iOS 7
barcelonaio
 
RESTfull with RestKit
RESTfull with RestKit
Taras Kalapun
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出
Ymow Wu
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
Michele Capra
 
Building Android apps with Parse
Building Android apps with Parse
DroidConTLV
 
How to execute an oracle stored procedure with nested table as a parameter fr...
How to execute an oracle stored procedure with nested table as a parameter fr...
Priyobroto Ghosh (Mule ESB Certified)
 
Birhanu distributive assignment
Birhanu distributive assignment
university
 

Viewers also liked (9)

Introduction to .NET with C# @ university of wayamba
Introduction to .NET with C# @ university of wayamba
Prageeth Sandakalum
 
ASP .NET Core MVC
ASP .NET Core MVC
Vinicius Mussak
 
.NET and C# introduction
.NET and C# introduction
Peter Gfader
 
Explorando o novo .NET multiplataforma: ASP.NET Core, .NET Core e EF Core
Explorando o novo .NET multiplataforma: ASP.NET Core, .NET Core e EF Core
Rogério Moraes de Carvalho
 
ASP.NET Core, .NET Core e EF Core: multiplataforma e otimizados para a nuvem
ASP.NET Core, .NET Core e EF Core: multiplataforma e otimizados para a nuvem
Rogério Moraes de Carvalho
 
Introduction to .NET Core
Introduction to .NET Core
Marco Parenzan
 
.NET and C# Introduction
.NET and C# Introduction
Siraj Memon
 
Introduction to .net framework
Introduction to .net framework
Arun Prasad
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform
Alex Thissen
 
Introduction to .NET with C# @ university of wayamba
Introduction to .NET with C# @ university of wayamba
Prageeth Sandakalum
 
.NET and C# introduction
.NET and C# introduction
Peter Gfader
 
Explorando o novo .NET multiplataforma: ASP.NET Core, .NET Core e EF Core
Explorando o novo .NET multiplataforma: ASP.NET Core, .NET Core e EF Core
Rogério Moraes de Carvalho
 
ASP.NET Core, .NET Core e EF Core: multiplataforma e otimizados para a nuvem
ASP.NET Core, .NET Core e EF Core: multiplataforma e otimizados para a nuvem
Rogério Moraes de Carvalho
 
Introduction to .NET Core
Introduction to .NET Core
Marco Parenzan
 
.NET and C# Introduction
.NET and C# Introduction
Siraj Memon
 
Introduction to .net framework
Introduction to .net framework
Arun Prasad
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform
Alex Thissen
 
Ad

Similar to Academy PRO: ASP .NET Core (20)

Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
Steven Smith
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
AMARAAHMED7
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6
Amin Mesbahi
 
ASP.NET Core 1.0
ASP.NET Core 1.0
Ido Flatow
 
Quick Interview Preparation Dot Net Core
Quick Interview Preparation Dot Net Core
Karmanjay Verma
 
.NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18
Amin Mesbahi
 
C#on linux
C#on linux
AvarinTalks
 
Full-Stack .NET Developer Interview Questions PDF By ScholarHat
Full-Stack .NET Developer Interview Questions PDF By ScholarHat
Scholarhat
 
ASP.NET Core For The Agile Enterprise
ASP.NET Core For The Agile Enterprise
Dennis Moon
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher
 
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
From Zero to Cloud in 12 Easy Factors
From Zero to Cloud in 12 Easy Factors
Ed King
 
Learn Cloud-Native .NET: Core Configuration Fundamentals with Steeltoe
Learn Cloud-Native .NET: Core Configuration Fundamentals with Steeltoe
VMware Tanzu
 
.NET Core, ASP.NET Core Course, Session 7
.NET Core, ASP.NET Core Course, Session 7
Amin Mesbahi
 
Asp.net core 2.0 security and identity
Asp.net core 2.0 security and identity
Talha Shahzad
 
Pathway to Cloud-Native .NET
Pathway to Cloud-Native .NET
VMware Tanzu
 
Google external login setup in ASP (1).pdf
Google external login setup in ASP (1).pdf
findandsolve .com
 
C# - Azure, WP7, MonoTouch and Mono for Android (MonoDroid)
C# - Azure, WP7, MonoTouch and Mono for Android (MonoDroid)
Stuart Lodge
 
.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8
Amin Mesbahi
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development
GlobalLogic Ukraine
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
Steven Smith
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
AMARAAHMED7
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6
Amin Mesbahi
 
ASP.NET Core 1.0
ASP.NET Core 1.0
Ido Flatow
 
Quick Interview Preparation Dot Net Core
Quick Interview Preparation Dot Net Core
Karmanjay Verma
 
.NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18
Amin Mesbahi
 
Full-Stack .NET Developer Interview Questions PDF By ScholarHat
Full-Stack .NET Developer Interview Questions PDF By ScholarHat
Scholarhat
 
ASP.NET Core For The Agile Enterprise
ASP.NET Core For The Agile Enterprise
Dennis Moon
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher
 
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
ASP.NET Core Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
From Zero to Cloud in 12 Easy Factors
From Zero to Cloud in 12 Easy Factors
Ed King
 
Learn Cloud-Native .NET: Core Configuration Fundamentals with Steeltoe
Learn Cloud-Native .NET: Core Configuration Fundamentals with Steeltoe
VMware Tanzu
 
.NET Core, ASP.NET Core Course, Session 7
.NET Core, ASP.NET Core Course, Session 7
Amin Mesbahi
 
Asp.net core 2.0 security and identity
Asp.net core 2.0 security and identity
Talha Shahzad
 
Pathway to Cloud-Native .NET
Pathway to Cloud-Native .NET
VMware Tanzu
 
Google external login setup in ASP (1).pdf
Google external login setup in ASP (1).pdf
findandsolve .com
 
C# - Azure, WP7, MonoTouch and Mono for Android (MonoDroid)
C# - Azure, WP7, MonoTouch and Mono for Android (MonoDroid)
Stuart Lodge
 
.NET Core, ASP.NET Core Course, Session 8
.NET Core, ASP.NET Core Course, Session 8
Amin Mesbahi
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development
GlobalLogic Ukraine
 
Ad

More from Binary Studio (20)

Academy PRO: D3, part 3
Academy PRO: D3, part 3
Binary Studio
 
Academy PRO: D3, part 1
Academy PRO: D3, part 1
Binary Studio
 
Academy PRO: Cryptography 3
Academy PRO: Cryptography 3
Binary Studio
 
Academy PRO: Cryptography 1
Academy PRO: Cryptography 1
Binary Studio
 
Academy PRO: Advanced React Ecosystem. MobX
Academy PRO: Advanced React Ecosystem. MobX
Binary Studio
 
Academy PRO: Docker. Part 4
Academy PRO: Docker. Part 4
Binary Studio
 
Academy PRO: Docker. Part 2
Academy PRO: Docker. Part 2
Binary Studio
 
Academy PRO: Docker. Part 1
Academy PRO: Docker. Part 1
Binary Studio
 
Binary Studio Academy 2017: JS team project - Orderly
Binary Studio Academy 2017: JS team project - Orderly
Binary Studio
 
Binary Studio Academy 2017: .NET team project - Unicorn
Binary Studio Academy 2017: .NET team project - Unicorn
Binary Studio
 
Academy PRO: React native - miscellaneous
Academy PRO: React native - miscellaneous
Binary Studio
 
Academy PRO: React native - publish
Academy PRO: React native - publish
Binary Studio
 
Academy PRO: React native - navigation
Academy PRO: React native - navigation
Binary Studio
 
Academy PRO: React native - building first scenes
Academy PRO: React native - building first scenes
Binary Studio
 
Academy PRO: React Native - introduction
Academy PRO: React Native - introduction
Binary Studio
 
Academy PRO: Push notifications. Denis Beketsky
Academy PRO: Push notifications. Denis Beketsky
Binary Studio
 
Academy PRO: Docker. Lecture 4
Academy PRO: Docker. Lecture 4
Binary Studio
 
Academy PRO: Docker. Lecture 3
Academy PRO: Docker. Lecture 3
Binary Studio
 
Academy PRO: Docker. Lecture 2
Academy PRO: Docker. Lecture 2
Binary Studio
 
Academy PRO: Docker. Lecture 1
Academy PRO: Docker. Lecture 1
Binary Studio
 
Academy PRO: D3, part 3
Academy PRO: D3, part 3
Binary Studio
 
Academy PRO: D3, part 1
Academy PRO: D3, part 1
Binary Studio
 
Academy PRO: Cryptography 3
Academy PRO: Cryptography 3
Binary Studio
 
Academy PRO: Cryptography 1
Academy PRO: Cryptography 1
Binary Studio
 
Academy PRO: Advanced React Ecosystem. MobX
Academy PRO: Advanced React Ecosystem. MobX
Binary Studio
 
Academy PRO: Docker. Part 4
Academy PRO: Docker. Part 4
Binary Studio
 
Academy PRO: Docker. Part 2
Academy PRO: Docker. Part 2
Binary Studio
 
Academy PRO: Docker. Part 1
Academy PRO: Docker. Part 1
Binary Studio
 
Binary Studio Academy 2017: JS team project - Orderly
Binary Studio Academy 2017: JS team project - Orderly
Binary Studio
 
Binary Studio Academy 2017: .NET team project - Unicorn
Binary Studio Academy 2017: .NET team project - Unicorn
Binary Studio
 
Academy PRO: React native - miscellaneous
Academy PRO: React native - miscellaneous
Binary Studio
 
Academy PRO: React native - publish
Academy PRO: React native - publish
Binary Studio
 
Academy PRO: React native - navigation
Academy PRO: React native - navigation
Binary Studio
 
Academy PRO: React native - building first scenes
Academy PRO: React native - building first scenes
Binary Studio
 
Academy PRO: React Native - introduction
Academy PRO: React Native - introduction
Binary Studio
 
Academy PRO: Push notifications. Denis Beketsky
Academy PRO: Push notifications. Denis Beketsky
Binary Studio
 
Academy PRO: Docker. Lecture 4
Academy PRO: Docker. Lecture 4
Binary Studio
 
Academy PRO: Docker. Lecture 3
Academy PRO: Docker. Lecture 3
Binary Studio
 
Academy PRO: Docker. Lecture 2
Academy PRO: Docker. Lecture 2
Binary Studio
 
Academy PRO: Docker. Lecture 1
Academy PRO: Docker. Lecture 1
Binary Studio
 

Recently uploaded (20)

Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
 
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
Y - Recursion The Hard Way GopherCon EU 2025
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Azure AI Foundry: The AI app and agent factory
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
The Anti-Masterclass Live - Peak of Data & AI 2025
The Anti-Masterclass Live - Peak of Data & AI 2025
Safe Software
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Sysinfo OST to PST Converter Infographic
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
Emvigo Capability Deck 2025: Accelerating Innovation Through Intelligent Soft...
Emvigo Capability Deck 2025: Accelerating Innovation Through Intelligent Soft...
Emvigo Technologies
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
Complete WordPress Programming Guidance Book
Complete WordPress Programming Guidance Book
Shabista Imam
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
A Guide to Telemedicine Software Development.pdf
A Guide to Telemedicine Software Development.pdf
Olivero Bozzelli
 
IObit Driver Booster Pro 12 Crack Latest Version Download
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
Y - Recursion The Hard Way GopherCon EU 2025
Y - Recursion The Hard Way GopherCon EU 2025
Eleanor McHugh
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
arctitecture application system design os dsa
arctitecture application system design os dsa
za241967
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Azure AI Foundry: The AI app and agent factory
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
Digital Transformation: Automating the Placement of Medical Interns
Digital Transformation: Automating the Placement of Medical Interns
Safe Software
 
The Anti-Masterclass Live - Peak of Data & AI 2025
The Anti-Masterclass Live - Peak of Data & AI 2025
Safe Software
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
Sysinfo OST to PST Converter Infographic
Sysinfo OST to PST Converter Infographic
SysInfo Tools
 
Emvigo Capability Deck 2025: Accelerating Innovation Through Intelligent Soft...
Emvigo Capability Deck 2025: Accelerating Innovation Through Intelligent Soft...
Emvigo Technologies
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 

Academy PRO: ASP .NET Core

  • 2. Contents 1. Intro 2. Startup 3. Middleware 4. Logging 5. Static files 6. Routing 7. Authentication 8. Configuration
  • 4. What is ASP.NET Core? leaner and modular architecture tighter security reduced servicing improved performance pay-for-what-you-use model.
  • 5. Why is ASP.NET Core? Integration of modern client-side frameworks and development workflows A cloud-ready environment-based configuration system Built-in dependency injection New light-weight and modular HTTP request pipeline (No System.Web.dll Ability to host on IIS or self-host in your own process Built on .NET Core, which supports true side-by-side app versioning Ships entirely as NuGet packages
  • 6. public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() // .UseServer("Microsoft.AspNet.Server.Kestrel") .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); }
  • 8. Configure - how the ASP.NET application will respond to individual HTTP requests. ConfigureServices - method for configuring services that are used by your application.
  • 9. Configure public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (!env.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
  • 10. ConfigureServices public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc(); // Add application services. services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); }
  • 12. Pipeline with IApplicationBuilder public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseExceptionHandler("/Home/Error"); // Middleware 1 app.UseStaticFiles(); // Middleware 2 app.UseIdentity(); // Middleware 3 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Middleware 4 }
  • 13. Custom pipeline public void ConfigureLogInline(IApplicationBuilder app, ILoggerFactory loggerfactory) { loggerfactory.AddConsole(minLevel: LogLevel.Information); var logger = loggerfactory.CreateLogger(_environment); app.Use(async (context, next) => { logger.LogInformation("Handling request."); await next.Invoke(); // Comment it to terminate the pipeline logger.LogInformation("Finished handling request."); }); app.Run(async context => { await context.Response.WriteAsync("Hello from " + _environment); }); }
  • 16. Simple logging [Route("api/[controller]")] public class TodoController : Controller { private readonly ITodoRepository _todoRepository; private readonly ILogger<TodoController> _logger; public TodoController(ITodoRepository todoRepository, ILogger<TodoController> logger) { _todoRepository = todoRepository; _logger = logger; } [HttpGet] public IEnumerable<TodoItem> GetAll() { _logger.LogInformation(LoggingEvents.LIST_ITEMS, "Listing all items"); return _todoRepository.GetAll(); } }
  • 17. Thirdparty Providers elmah.io - provider for the elmah.io service Loggr - provider for the Loggr service NLog - provider for the NLog library Serilog - provider for the Serilog library your own
  • 19. Set directory to content: public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } Set static files to pipeline: public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")), RequestPath = new PathString("/StaticFiles") }); }
  • 20. Content type mapping public void Configure(IApplicationBuilder app) { // Set up custom content types -associating file extension to MIME type var provider = new FileExtensionContentTypeProvider(); // Add new mappings provider.Mappings[".myapp"] = "application/x-msdownload"; provider.Mappings[".htm3"] = "text/html"; provider.Mappings[".image"] = "image/png"; // Replace an existing mapping provider.Mappings[".rtf"] = "application/x-msdownload"; // Remove MP4 videos. provider.Mappings.Remove(".mp4"); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"wwwrootimages")), RequestPath = new PathString("/MyImages"), ContentTypeProvider = provider }); }
  • 22. URL Matching Request Route 1 Route 2 Route N RouterMiddleware .RouteAsync() Handle() Next()
  • 23. Mapping routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "us_english_products", template: "en-US/Products/{id}", defaults: new { controller = "Products", action = "Details" }, constraints: new { id = new IntRouteConstraint() }, dataTokens: new { locale = "en-US" });
  • 24. Routing Middleware public void ConfigureServices( IServiceCollection services) { services.AddRouting(); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { var trackPackageRouteHandler = new RouteHandler(context => { var routeValues = context.GetRouteData().Values; return context.Response.WriteAsync( $"Hello! Route values: {string.Join(", ", routeValues)}"); }); var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler); routeBuilder.MapRoute( "Track Package Route", "package/{operation:regex(^track|create|detonate$)}/{id:int}"); routeBuilder.MapGet("hello/{name}", context => { var name = context.GetRouteValue("name"); return context.Response.WriteAsync($"Hi, {name}!"); }); var routes = routeBuilder.Build(); app.UseRouter(routes);
  • 27. Identity // Authentication should be set to Individual User Accounts // ConfigureServices services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // Configure app.UserIdentity(); // Manage users UserManager<ApplicationUser> _usermanager; // Manage sign in/sign out SignInManage<ApplicationUser> _signinmanager;
  • 28. Facebook, Twitter, Google Providers app.UseFacebookAuthentication(new FacebookOptions() { AppId = Configuration["Authentication:Facebook:AppId"], AppSecret = Configuration["Authentication:Facebook:AppSecret"] }); // Other providers use similar approach
  • 29. Other Features Two-factor authentication with SMS Supporting Third Party Clients using OAuth 2.0 Azure Active Directory Securing ASP.NET Core apps with IdentityServer4
  • 31. var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json"); builder.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); builder.AddCommandLine(args); var connectionStringConfig = builder.Build(); var str = connectionStringConfig.GetConnectionString("DefaultConnection")
  • 32. IOptions // ConfigureServices services.AddOptions(); services.Configure<MyOptions>(Configuration); // Configure MyOptions using code services.Configure<MyOptions>(myOptions => { myOptions.Option1 = "value1_from_action"; myOptions.Option2 = connectionStringConfig.GetConnectionString("DefaultConnection"); }); public class HomeController : Controller { private readonly IOptions<MyOptions> _optionsAccessor; public HomeController(IOptions<MyOptions> optionsAccessor) { _optionsAccessor = optionsAccessor; } // GET: /<controller>/ public IActionResult Index() => View(_optionsAccessor.Value); } public class MyOptions { public string Option1 { get; set; } public string Option2 { get; set; } }
  • 34. Exception Handling Page // Configure if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); }
  • 35. Status Code Pages // Configure app.UseStatusCodePages(); app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain")); app.UseStatusCodePages("text/plain", "Response, status code: {0}"); app.UseStatusCodePagesWithRedirects("~/errors/{0}"); app.UseStatusCodePagesWithReExecute("/errors/{0}");
  • 36. ASP.NET MVC Handling Exception filters Model validation
  • 38. Swagger is a machine readable representation of a RESTful API Swashbuckle is an open source project for generating Swagger documents for Web APIs
  • 39. Set Up // Install package Install-Package Swashbuckle -Pre Add Swashbuckle to project.json: "Swashbuckle": "6.0.0-beta902" // Configure // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUi(); // ConfigureServices // Inject an implementation of ISwaggerProvider with defaulted settings applied services.AddSwaggerGen();