Professional Documents
Culture Documents
Core
Core
Status Code:
All HTTP response status code are divided into five categories.
2XX- Successful.
3XX- Redirection.
200 – Ok
204 – No content (the server processed the request successfully and it is not returning the content.
405 – Method not allowed (There is HTTPGet, HttpPUT, post if you use other method rather than actual
method then you will get this error).
Launchsettin.json file: -
Host builder is an object and it is used to add some features in the application.
CreateDefaultBuilder Method provides the below functionality (to read the setting, to configure the
setting).
Will get,
Logging
Note: - if you change the name of CreateHostBuilder Method it will be fine if you use some basic
configuration if you use EF core then this method is must. EF core search this method to some default
configuration.
ConfigureWebHostDefaults:
Startup Class
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace WebAPIDemo
{
public class Startup
{
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace WebAPIDemo
{
public class Startup
{
}
}
ControllerBase : -
The ControllerBase class provides many method and properties to handle the HTTP request.
APIController:-
Middleware:-
Custom Middleware:
RequestDelegate : The request delegate handle each HTTP request. Request delegate are
configured using Run, Map, Use extension method.
HttpContext : encapsulates all the Http-specific information.
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace WebAPIDemo
{
public class CustomMiddleware:IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await context.Response.WriteAsync("Hello from custom middleware");
}
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseMiddleware<CustomMiddleware>();
}
App.Map(“/testmap”, MapCustomMiddleware);
With this when the request comes, if it contains /testmap as part of the URL, then only this
Middleware component going to be executed else simply is ignored.
How to enable routing
[controller]/[action]
[ApiController]
[Route(“[controller]/[action]”)]
[(“Id”)]
Return Type
Model Binder
Bind the incoming HTTP request data to the action method parameter.
[BindProperty]: -
BindProperty is an attribute and it is used to bind the incoming form-data to the public properties of
controller.
If you want to enable the property with GET method then [BindProperty (supportget=true)].
[BindProperties]:-
Lifetime of Services in DI
Singleton
Scoped
Transient
Singleton
Scoped
Transient
Now if you use the Try version like TryAddScoped then it will only register the service if it was not
registered earlier. In case service was already registered then the TryAddScoped will skip the registration
for that service.
Services.TryAddTransient<IProductRepository, TestRepository>();
Identity Core
Identity core has everything that is required to work with authentication and authorization.
If you want to add extra properties then create a new class ex (ApplicationUser) inherit
it from IdentityDbContext<ApplicationUser>
services.AddIdentity<ApplicationUser,IdentityRole>()
.AddEntityFrameworkStores<BookStoreDBContext>()
.AddDefaultTokenProviders();
JWT
Install Microsoft.AspNetCore.Authentication.JwtBearer
"JWT":{
"ValidAudience":"User",
"ValidIssuer":"https://localhost:5001
",
"Secret":"BookStore@1234"
}
services.AddAuthentication(option=>{
option.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
option.DefaultScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(option=>{
option.SaveToken=true;
option.RequireHttpsMetadata=false;
option.TokenValidationParameters=new
Microsoft.IdentityModel.Tokens.TokenValidationParameters(){
ValidateIssuer=true,
ValidateAudience=true,
ValidAudience=Configuration["JWT:ValidAudience"],
ValidIssuer=Configuration["JWT:ValidIssuer"],
IssuerSigningKey= new
SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["JWT:Secret
"]))
};
});
InProcess and OutProcess
InProcess: is the default hosting model. This means requests forwarded to IIS HTTP server.
OutProcess: it uses kestrel web server (dotnet.exe). It is using two web servers (IIS, Nginx, and
Apache).
The host configures a server like kestrel or IIS and a request processing pipeline.
App. UseExceptionHandler(“/error”).
App. UseDeveloperExceptionPage();
Interface IEmployeeRepository
{
Task<EmployeeResult> GetAllEmployees();
}
Step 3:
Register services.AddMemoryCache() to ConfigureServices() method in the Startup class.
AbsoluteExpiration = DateTime.Now.AddMinutes(5),
SlidingExpiration = TimeSpan.FromMinutes(2),
Size = 1024,
};
return Ok(employees);
What is MediaTypeFormatter
MediaTypeFormatter is an abstract class from
which JsonMediaTypeFormatter and XmlMediaTypeFormatter classes inherit from.
JsonMediaTypeFormatter handles JSON and XmlMediaTypeFormatter handles XML.
How to return only JSON from ASP.NET Web API Service irrespective of the Accept
header value
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("text/html"));