SlideShare une entreprise Scribd logo
1  sur  39
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();

Contenu connexe

Tendances

Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on Java
Max Titov
 
What's new in iOS 7
What's new in iOS 7What's new in iOS 7
What's new in iOS 7
barcelonaio
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
Taras Kalapun
 

Tendances (20)

Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
Spring java config
Spring java configSpring java config
Spring java config
 
Url programming
Url programmingUrl programming
Url programming
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Simple blog wall creation on Java
Simple blog wall creation on JavaSimple blog wall creation on Java
Simple blog wall creation on Java
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Spring4 whats up doc?
Spring4 whats up doc?Spring4 whats up doc?
Spring4 whats up doc?
 
Programming IoT Gateways with macchina.io
Programming IoT Gateways with macchina.ioProgramming IoT Gateways with macchina.io
Programming IoT Gateways with macchina.io
 
Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Intro to Parse
Intro to ParseIntro to Parse
Intro to Parse
 
What's new in iOS 7
What's new in iOS 7What's new in iOS 7
What's new in iOS 7
 
What's Parse
What's ParseWhat's Parse
What's Parse
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Building Android apps with Parse
Building Android apps with ParseBuilding Android apps with Parse
Building Android apps with Parse
 
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...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...
 
Birhanu distributive assignment
Birhanu distributive assignmentBirhanu distributive assignment
Birhanu distributive assignment
 

En vedette

Introduction to .NET with C# @ university of wayamba
Introduction to .NET with C# @ university of wayambaIntroduction to .NET with C# @ university of wayamba
Introduction to .NET with C# @ university of wayamba
Prageeth Sandakalum
 

En vedette (9)

Introduction to .NET with C# @ university of wayamba
Introduction to .NET with C# @ university of wayambaIntroduction to .NET with C# @ university of wayamba
Introduction to .NET with C# @ university of wayamba
 
ASP .NET Core MVC
ASP .NET Core MVCASP .NET Core MVC
ASP .NET Core MVC
 
.NET and C# introduction
.NET and C# introduction.NET and C# introduction
.NET and C# introduction
 
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 CoreExplorando 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
 
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 nuvemASP.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
 
Introduction to .NET Core
Introduction to .NET CoreIntroduction to .NET Core
Introduction to .NET Core
 
.NET and C# Introduction
.NET and C# Introduction.NET and C# Introduction
.NET and C# Introduction
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET Platform
 

Similaire à Academy PRO: ASP .NET Core

Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
FIWARE
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web applicationASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
AMARAAHMED7
 
Nuxeo - OpenSocial
Nuxeo - OpenSocialNuxeo - OpenSocial
Nuxeo - OpenSocial
Thomas Roger
 

Similaire à Academy PRO: ASP .NET Core (20)

C#on linux
C#on linuxC#on linux
C#on linux
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Java Web Programming on Google Cloud Platform [1/3] : Google App Engine
Java Web Programming on Google Cloud Platform [1/3] : Google App EngineJava Web Programming on Google Cloud Platform [1/3] : Google App Engine
Java Web Programming on Google Cloud Platform [1/3] : Google App Engine
 
Google App Engine
Google App EngineGoogle App Engine
Google App Engine
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
 
Servlets
ServletsServlets
Servlets
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
Saving Time And Effort With QuickBase Api - Sergio Haro
Saving Time And Effort With QuickBase Api - Sergio HaroSaving Time And Effort With QuickBase Api - Sergio Haro
Saving Time And Effort With QuickBase Api - Sergio Haro
 
File Repository on GAE
File Repository on GAEFile Repository on GAE
File Repository on GAE
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
The Google App Engine Oil Framework
The Google App Engine Oil FrameworkThe Google App Engine Oil Framework
The Google App Engine Oil Framework
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web applicationASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
 
Nuxeo - OpenSocial
Nuxeo - OpenSocialNuxeo - OpenSocial
Nuxeo - OpenSocial
 
ASP.NET Core 1.0
ASP.NET Core 1.0ASP.NET Core 1.0
ASP.NET Core 1.0
 
Arquitecturas de microservicios - Medianet Software
Arquitecturas de microservicios   -  Medianet SoftwareArquitecturas de microservicios   -  Medianet Software
Arquitecturas de microservicios - Medianet Software
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Building microservices sample application
Building microservices sample applicationBuilding microservices sample application
Building microservices sample application
 

Plus de Binary Studio

Plus de Binary Studio (20)

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

Dernier

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Dernier (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 

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();