European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET Core Hosting - HostForLIFE.eu :: ASP.NET Core Security Headers

clock April 30, 2019 11:13 by author Peter

With the help of headers, your website could send some useful information to the browser. Let’s see how it is possible to add more protection to your website.
To add a header for each request, we can use middleware.

XSS and CSP
Still in the OWASP top 10, there is XSS - Cross-Site Scripting attack. Sure, it helps a lot to encode symbols before displaying text on the website (using any one of the HtmlEncoder, JavaScriptEncoder, and UrlEncoder). And, it’s better never to use @Html.Raw(). But it is also possible to add a header that will inform the browser to stop XSS attack. This kind of header is useful mostly for old browsers.
app.Use(async (context, next) =>  
{  
context.Response.Headers.Add("X-Xss-Protection", "1");  
await next();  
}); 


For new browsers, it is better to use CSP. Here is how it is possible to add the CSP header.
app.Use(async (context, next) =>  
{  
context.Response.Headers.Add(  
  "Content-Security-Policy",  
  "default-src 'self'; " +  
  "img-src 'self' myblobacc.blob.core.windows.net; " +  
  "font-src 'self'; " +  
  "style-src 'self'; " +  
  "script-src 'self' 'nonce-KIBdfgEKjb34ueiw567bfkshbvfi4KhtIUE3IWF' "+  
  " 'nonce-rewgljnOIBU3iu2btli4tbllwwe'; " +  
  "frame-src 'self';"+  
  "connect-src 'self';");  
await next();  
});  


In this example, it is allowed to run scripts.js files only from the current website (that is a meaning of ‘self’). And it is allowed to run 2 specified with “nonce” attribute scripts that are inserted in page inside script tag. For example, if you are using some script like this one inside your page.
<script>  
function showMessage() {  
alert("Just for demo");  
}   
</script>  

Then, you will be not able to run this script without adding ‘unsafe-inline’ into your CSP definition.

But adding ‘unsafe-inline’ means leaving your website not-protected. So, better move the script into .js file or use a nonce. Just add to your script attribute nonce with some random value. For example,
<script nonce="KUY8VewuvyUYVEIvEFue4vwyiuf"> </script>  

Then, you can add to your CSP script-scr value ‘nonce-KUY8VewuvyUYVEIvEFue4vwyiuf’ and you will be able to run scripts from exactly this <script> section.

‘unsafe-inlne’ is also related to events that are added to your html as attributes. Like onclick, onchange, onkeydown, onfocus. For example, instead of the following onclick event, you should add id or class to your element and call event from <script> or .js file.
<p onclick="showMessage()">Show message</p>  

Like this,
<p id="message-text">Show message</p>  

<script nonce=”KUY8VewuvyUYVEIvEFue4vwyiuf”>  
$(document).ready(function() {  
$("#message-text") (function() {  
alert( "Just for demo" );  
});   
});  
</script>  


X-Frame-Options
By default, it is possible to display your website inside an iframe. But with one small header, it is possible to disallow this. Why? Because someone could display your website inside a frame and place a transparent layer over it. And, the users would be thinking that they are clicking on your website buttons/links but in a real case, they would be clicking on items placed in the transparent layer. And as cookies still could be in the user’s browser, some operation could be authenticated. This kind of attack is called Clickjacking. And, here is a header to protect your website from this attack.
context.Response.Headers.Add("X-Frame-Options", "DENY");  

Content sniffing
By the next link File Upload XSS you can find a more or less fresh sample of how it is possible to inject JavaScript into an svg file. And if a file like this would be located on the server that would have content sniffing security enabled, then JavaScript wouldn’t work because svg extension doesn’t correspond to JS content. Hope you believe me now that the next header is required.
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");  

Referrer-Policy
One of the headers that is automatically added by browsers is “Referer”. It contains a site from which the user has been transferred. Sometimes, that is convenient for analytics. But sometimes, the URL could contain some private information that is better not to be disclosed.

If you don’t want to allow browsers to display your website as last visited in “Referer” header, please use the Referrer-Policy: no-referrer

Here is an example of all headers in one middleware.
app.Use(async (context, next) =>  
{  
context.Response.Headers.Add("X-Xss-Protection", "1");  
context.Response.Headers.Add("X-Frame-Options", "DENY");  
context.Response.Headers.Add("Referrer-Policy", "no-referrer");  
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");  
              context.Response.Headers.Add(  
  "Content-Security-Policy",  
  "default-src 'self'; " +  
  "img-src 'self' myblobacc.blob.core.windows.net; " +  
  "font-src 'self'; " +  
  "style-src 'self'; " +  
  "script-src 'self' 'nonce-KIBdfgEKjb34ueiw567bfkshbvfi4KhtIUE3IWF' "+  
  " 'nonce-rewgljnOIBU3iu2btli4tbllwwe'; " +  
  "frame-src 'self';"+  
  "connect-src 'self';");  
await next();  
});  


Sure, you can read information about each one header and change value to something more appropriate for your needs.
Strict-Transport-Security

For activating Strict-Transport-Security - web security policy mechanism that helps to protect your website from protocol downgrade attacks and cookie hijacking, add the next one to your middleware pipeline (or just don’t remove it),
app.UseHsts();  

This middleware will add “Strict-Transport-Security” header

Removing Server Header
Sometimes, headers could provide some information that is better to hide. To disable the Server header from Kestrel, you need to set AddServerHeader to false. Use UseKestrel() if your ASP.NET Core version is  lower than 2.2 and ConfigureKestrel() if not.
WebHost.CreateDefaultBuilder(args)  
     .UseKestrel(c => c.AddServerHeader = false)  
     .UseStartup<Startup>()  
     .Build();



European ASP.NET Core Hosting :: Create A Typed HttpClient With

clock April 23, 2019 10:57 by author Peter

HttpClient is used for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. But, HttpClient has some issues. To read more on the issues of HttpClient, you can check this link. In the .NET Core 2.1 release, Microsoft has introduced a new way of designing HttpClients to solve these issues, and it's called HttpClientFactory. HttpClientFactory is an opinionated factory, available since .NET Core 2.1, for creating HttpClient instances in our applications. This means that we can create HttpClients and can register them in the HttpClientFactory in our application and can leverage the dependency injection capabilities of the .NET core to inject these HttpClients in our code. HttpClientFactory allows us to no longer care about the lifecycle of the HttpClient by leaving it to the framework.
 
There are three ways to use HttpClientFactory to instantiate HttpClients.

  • Default client
  • Named client
  • Typed client

In order to use the factory, we need to register it in the DI container. So, we need to use an extension method AddHttpClient() on IServiceCollection interface in our Startup.cs class. This will allow us to inject the HttpClient in our class constructors.
 
In this article, we will see how to create a Typed HttpClient using the HttpClient factory in a .NET core MVC application and use it for making HTTP calls. I prefer Typed HttpClient over the other two because,

    As the name suggests, typed clients provide type safety.
    Typed clients help in encapsulating the API calls when we are making use of the HttpClient at one place, thus making our code DRY (Don't Repeat Yourself). The other two will scatter the implementation details of making HTTP calls throughout the codebase.

We will make a simple MVC application to learn the workings of typed HttpClient. This application will receive the name of a movie and call a REST API to fetch the details of that movie and shall display it to the user. I will be using Visual Studio Code for developing the application. The REST API used for fetching the movie details is the OMDB API. The OMDB API is a RESTful web service to obtain movie information. This is a free API with a 1000 requests per day limit for a user. We need an API key for accessing this API. To know more details about this API you can check their website.

Create a folder called MovieFinder and open it in VS Code. Create an MVC application by running the following command in the terminal.
    dotnet new mvc --name MovieFinder 

This shall create a basic .NET Core MVC application. Now, let’s create a View Model class to hold the data from the OMDB API. So, let’s add a class named MovieDetailModel.
    public class MovieDetailModel 
    { 
        public string Title { get; set; } 
        public string Year { get; set; } 
        public string Director { get; set; } 
        public string Actors { get; set; } 
        public string IMDBRating { get; set; } 
        public string PosterImage { get; set; } 
        public string Plot { get; set; } 
    } 


Now, we need to create an interface for our typed client. Let's name it IMovieDetailsClient.
    public interface IMovieDetailsClient 
    { 
        Task<MovieDetailModel> GetMovieDetailsAsync(string movieName); 
    } 


This interface contains a single method, GetMovieDetailsAsync, which accepts the movie name as the parameter and shall return the details of that movie. Now we need to create a class which implements this interface. This class shall contain the actual logic of calling the OMDB API to fetch the movie details.
    public class MovieDetailsClient : IMovieDetailsClient 
    { 
        private readonly HttpClient _httpClient; 
     
        public MovieDetailsClient(HttpClient httpClient) 
        { 
            httpClient.BaseAddress = new Uri("http://www.omdbapi.com/"); 
            _httpClient = httpClient; 
        } 
     
        public async Task<MovieDetailModel> GetMovieDetailsAsync(string movieName) 
        { 
            var queryString = $"?t={movieName}&apikey=<your-api-key>"; 
            var response = await _httpClient.GetStringAsync(queryString); 
     
            JObject json = JObject.Parse(response); 
     
            if (json.SelectToken("Response").Value<string>() == "True") 
            { 
     
                var movieDetails = new MovieDetailModel 
                { 
                    Title = json.SelectToken("Title").Value<string>(), 
                    Year = json.SelectToken("Year").Value<string>(), 
                    Director = json.SelectToken("Director").Value<string>(), 
                    Actors = json.SelectToken("Actors").Value<string>(), 
                    IMDBRating = json.SelectToken("imdbRating").Value<string>(), 
                    PosterImage = json.SelectToken("Poster").Value<string>(), 
                    Plot = json.SelectToken("Plot").Value<string>() 
                }; 
     
                return movieDetails; 
            } 
     
            return new MovieDetailModel 
            { 
                Title = movieName 
            }; 
        } 
    } 


In this class, we inject the HttpClient in our class constructor and set the base address of our OMDB API endpoint. We also implement GetMovieDetailsAsync method declared in our interface. We called the OMDB API from our method and mapped the API response to our view model and returned it. I have used the JSON.NET library for parsing the response from the API.
Note that I have hardcoded the API Base address and the API key in the code. This is not a healthy practice. We shall always prefer moving these kinds of values to configuration files and shall read those values from the configuration files in our code.
 
We have now created our typed client. Now let's create the view for user interaction. In the Index.cshtml file in the Views\Home folder, replace the existing code with the following code.
    @{ 
        ViewData["Title"] = "Home Page"; 
    } 
     
    @model MovieDetailModel 
     
    <form  
        asp-controller="Home"  
        asp-action="Submit" 
        method="post"  
        class="form-horizontal"  
        role="form"> 
     
        <div class="form-group"> 
            <label for="Title">Title</label> 
            <input  
                class="form-control"  
                placeholder="Enter Title" 
                asp-for="Title">    
        </div> 
        <button type="submit" class="btn btn-primary">Submit</button> 
    </form> 
     
     
    @{ 
        <br> 
         
        if(!string.IsNullOrEmpty(Model?.Year)) 
        { 
            var title = Model.Title; 
            var year = Model.Year;   
            var message = $"{title} is release on {year}";  
      
            <br> 
            <div class="card" style="width: 18rem;"> 
                <img class="card-img-top" [email protected] alt="Poster Not Available"> 
                <div class="card-body"> 
                    <h5 class="card-title">@Model.Title (@Model.Year)</h5> 
                    <p class="card-text">@Model.Plot</p>               
                </div> 
                <ul class="list-group list-group-flush"> 
                    <li class="list-group-item"><strong>Director : @Model.Director</strong></li> 
                    <li class="list-group-item"><strong>Actors : @Model.Actors</strong></li> 
                    <li class="list-group-item"><strong>Rating : @Model.IMDBRating</strong></li> 
                </ul> 
            </div>      
        } 
         
        if(Model != null && string.IsNullOrEmpty(Model?.Year)) 
        { 
            <div class="alert alert-danger" role="alert"> 
                <strong>Sorry!! Requested Movie Details are not available..</strong>  
            </div> 
        } 
    } 


Now, we need to add the Controller code for accepting the movie name from the view and for displaying the movie details. For that, we need to inject the typed client we had created into the constructor of our controller. So, we need to register this typed client with the HttpClient factory in our Startup.cs class. Add the following code in the ConfigureServices method in the startup class.
    services.AddHttpClient<IMovieDetailsClient, MovieDetailsClient>(); 

Now, let's add our controller methods. In the HomeController make the changes as below.
    public class HomeController : Controller 
    { 
        private readonly IMovieDetailsClient _movieDetailsClient; 
     
        public HomeController(IMovieDetailsClient movieDetailsClient) 
        { 
            _movieDetailsClient = movieDetailsClient; 
        } 
     
        public IActionResult Index() 
        { 
            return View(); 
        } 
     
        [HttpPost] 
        public async Task<IActionResult> Submit(MovieDetailModel model) 
        { 
            var movieDetail = await _movieDetailsClient.GetMovieDetailsAsync(model.Title); 
            return View("Index", movieDetail); 
        }       
    } 


We are injecting our IMovieDetails client in the constructor of our controller and assigning it to a read-only field _movieDetailsClient. We have also defined an action named Submit which takes the title of the movie from the view as a parameter. This method makes use of our typed HttpClient to fetch the details of that movie and shall return the view with the details of that movie.

Now, run the application. Execute the command dotnet run in the terminal. Open a browser and navigate to https://localhost:5001/.

 



European ASP.NET Core Hosting - HostForLIFE.eu :: Javascript, CSS, HTML in ASP.NET Core

clock April 12, 2019 09:45 by author Scott

This article will teach you how to include and customize the use of static files in ASP .NET Core web applications. It is not a tutorial on front-end web development.

If your ASP .NET Core web app has a front end – whether it’s a collection of MVC Views or a Single-Page Application (SPA) – you will need to include static files in your application. This includes (but is not limited to): JavaScript, CSS, HTML and various image files.

When you create a new web app using one of the built-in templates (MVC or Razor Pages), you should see a “wwwroot” folder in the Solution Explorer. This points to a physical folder in your file system that contains the same files seen from Visual Studio. However, this location can be configured, you can have multiple locations with static files, and you can enable/disable static files in your application if desired. In fact, you have to “opt in” to static files in your middleware pipeline.

Configuring Static Files via Middleware

Let’s start by observing the Startup.cs configuration file. We’ve seen this file several times throughout this blog series. In the Configure() method, you’ll find the familiar method call to enable the use of static files.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   ...
   app.UseStaticFiles();
   ...
   app.UseMvc(...);
}

This call to app.UseStaticFiles() ensures that static files can be served from the designated location, e.g. wwwroot.

It’s useful to note the placement of this line of code. It appears before app.UseMvc(), which is very important. This ensures that static file requests can be processed and sent back to the web browser without having to touch the MVC middleware. This becomes even more important when authentication is used.

In the code below, you can see the familiar call to app.UseStaticFiles() once again. However, there is also a call to app.UseAuthentication(). It’s important for the authentication call to appear after the call to use static files. This ensure that the authentication process isn’t triggered when it isn’t needed.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   ...
   app.UseStaticFiles();
   ...
   app.UseAuthentication();
   ...
   app.UseMvc(...);
}

By using the middleware pipeline in this way, you can “short-circuit” the pipeline when a request has been fulfilled by a specific middleware layer. If a static file has been successfully served using the Static Files middleware, it prevents the next layers of middleware (i.e. authentication, MVC) from processing the request.

Customizing Locations for Static Files

It may be convenient to have the default web templates create a location for your static files and also enable the use of those static files. As you’ve already seen, enabling static files isn’t magic. Removing the call to app.useStaticFiles() will disable static files from being served. In fact, the location for static files isn’t magic either.

public class Program
{
   ...
   public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
      WebHost.CreateDefaultBuilder(args)
         .UseStartup<Startup>();
}

Behind the scenes, this method call sets the “content root” to the current directory, which contains the “wwwroot” folder, your project’s “web root”. These can both be customized.

WebHost.CreateDefaultBuilder(args).UseContentRoot("c:\\<content-root>")

WebHost.CreateDefaultBuilder(args).UseWebRoot("public")

You may also use the call to app.UseStaticFiles() to customize an alternate location to serve static files. This allows you to serve additional static files from a location outside of the designated web root.

...
using Microsoft.Extensions.FileProviders;
using System.IO;
...
public void Configure(IApplicationBuilder app)
{
   ...
   app.UseStaticFiles(new StaticFileOptions
   {
      FileProvider = new PhysicalFileProvider
         Path.Combine(env.ContentRootPath, "AltStaticRoot")),
         RequestPath = "/AltStaticFiles"
   });
}

Wait a minute… why does it look like there are two alternate locations for static files? There is a simple explanation:

  • In the call to Path.Combine(), the “AltStaticRoot” is an actual folder in your current directory. This Path class and its Combine() method are available in the System.IO namespace.
  • The “AltStaticFiles” value for RequestPath is used as a root-level “virtual folder” from which images can be served. The PhysicalFileProvider class is available in the Microsoft.Extensions.FileProviders namespace.

The following markup may be used in a .cshtml file to refer to an image, e.g. MyImage01.png:

<img src="~/AltStaticFiles/MyImages/MyImage01.png" />

The screenshot below shows an example of an image loaded from an alternate location.

The screenshot below shows a web browser displaying such an image.

Preserving CDN Integrity

When you use a CDN (Content Delivery Network) to serve common CSS and JS files, you need to ensure that the integrity of the source code is reliable. You can rest assured that ASP .NET Core has already solved this problem for you in its built-in templates.

<environment include="Development">
 <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
</environment>

<environment exclude="Development">
 <link
   rel="stylesheet"
   href=
https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css
   asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
   asp-fallback-test-class="sr-only"
   asp-fallback-test-property="position"
   asp-fallback-test-value="absolute"
   crossorigin="anonymous"
   integrity="sha256-eSi1q2PG6J7g7ib17yAaWMcrr5GrtohYChqibrV7PBE="/>
</environment>

Right away, you’ll notice that there are two conditional <environment> blocks in the above markup. The first block is used only during development, in which the bootstrap CSS file is obtained from your local copy. When not in development (e.g. staging, production, etc), the bootstrap CSS file is obtained from a CDN, e.g. CloudFlare.

You could use an automated hash-generation tool to generate the SRI (Subresource Integrity) hash values, but you would have to manually copy the value into your code. You can try out the relatively-new LibMan (aka Library Manager) for easily adding and updating your client-side libraries.

LibMan (aka Library Manager)

The easiest way to use LibMan is to use the built-in features available in Visual Studio. Using LibMan using the IDE is as easy as launching it from Solution Explorer. Specify the provider from the library you want, and any specific files you want from that library.

In the popup that appears, select/enter the following:

  • Provider: choose from cdnjs, filesystem, unpkg
  • Library search term, e.g. @aspnet/signalr@1… pick latest stable if desired
  • Files: At a minimum, choose specific files, e.g. signalr.js and/or its minified equivalent

 

For more on LibMan (using VS or CLI), check out the official docs:

Use LibMan with ASP.NET Core in Visual Studio: https://docs.microsoft.com/en-us/aspnet/core/client-side/libman/libman-vs

Use the LibMan command-line interface (CLI): https://docs.microsoft.com/en-us/aspnet/core/client-side/libman/libman-cli

Library Manager: Client-side content manager for web apps: https://devblogs.microsoft.com/aspnet/library-manager-client-side-content-manager-for-web-apps/

In any case, using LibMan will auto-populate a “libman.json” manifest file, which you can also inspect and edit manually.

{
  "version": "1.0",
  "defaultProvider": "unpkg",
  "libraries": [
    {
      "library": "@aspnet/[email protected]",
      "destination": "wwwroot/lib/signalr/",
      "files": [
        "dist/browser/signalr.js",
        "dist/browser/signalr.min.js"
      ]
    }
  ]
}

What About NPM or WebPack?

If you’ve gotten this far, you may be wondering: “hey, what about NPM or WebPack?”

It’s good to be aware that LibMan is a not a replacement for your existing package management systems. In fact, the Single-Page Application templates in Visual Studio (for Angular and React) currently use npm and WebPack. LibMan simply provides a lightweight mechanism to include client-side libraries from external location.

 



European ASP.NET Core Hosting :: RESTful WebAPI With Onion Architecture

clock April 9, 2019 11:29 by author Peter

Hello friends, here I will show you how to create a WebApi with the following characteristics:

  • ASP.Core 2.1
  • EntityFramework
  • FluentValidation
  • Nlogger
  • Swagger
  • Jwt

Let's start. First create an empty project, then add the following folders:

  • Application
  • Domain
  • Service
  • Infrastructure

Then in the Domain folder, we create a library project Net.Core 2.1 with the name WebApi.Domain add the following dependencies

FluentValidation.AspNetCore

In this project, we add the following folders:

  • Dtos
  • Entities
  • Interfaces

In the Entities folder, we create the BaseEntity class:

    namespace WebApi.Domain.Entities 
    { 
        public abstract class BaseEntity 
        { 
            public virtual int Id { get; set; } 
        } 
    } 

Our project classes will inherit the field Id from this abstract class (if you want you can add other fields like CreatedAt or CreatedBy).

Then we create the Country class with the properties that defines a Country.

    namespace WebApi.Domain.Entities 
    { 
        public class Country : BaseEntity 
        { 
            public string Name { get; set; } 
            public int Population { get; set; } 
            public decimal Area { get; set; } 
            public string ISO3166 { get; set; } 
            public string DrivingSide { get; set; } 
            public string Capital { get; set; } 
     
        } 
    } 

Now to make the exercise more interesting, we are going to assume that we do not want to expose all the Country class. In the Dtos folder, we create the following CountryDensityDTO class.

    using System; 
    using WebApi.Domain.Entities; 
     
    namespace WebApi.Domain.Dtos 
    { 
        public class CountryDensityDTO : BaseEntity 
        { 
            public string Name { get; set; } 
            public string Capital { get; set; } 
            public decimal Area { get; set; } 
            public int Population { get; set; } 
     
     
            public int Populationdensity 
            { 
                get 
                { 
                    return Decimal.ToInt32(Population / Area); 
                } 
            } 
        } 
    }

This class exposes Name, Capital Area, Population and a calculated field Populationdensity.
Now we will continue with the Infrastructure layer and then we will finish the missing parts.We go to the Infrastructure folder and create a library Net.Core 2.1. We name it WebApi.Infrastructure.Data.

We add the following Packages:

  • Microsoft.EntityFrameworkCore.SqlServer 2.1.4
  • Microsoft.EntityFrameworkCore.Tools 2.1.4
  • Microsoft.Extensions.Identity.Stores 2.1.1
  • Microsoft.VisualStudio.Web.CodeGeneration.Design 2.1.5
  • Add Project reference WebApi.Domain 

We create the following folders:

  • Context
  • EntityDbMapping
  • Repository

In the Context Folder, we add the SqlServerContext class. We refer to our Country entity with DbSet to work with the database. As we work with CodeFirst approach, we will create a mapping for our entity Country in the database.
"modelBuilder.Entity<Country>(new CountryMap().Configure);"

Optionally, in this part we can also add seed data when creating a table.

using Microsoft.AspNetCore.Identity.EntityFrameworkCore; 
using Microsoft.EntityFrameworkCore; 
using WebApi.Domain.Entities; 
using WebApi.Infrastructure.Data.EntityDbMapping; 

namespace WebApi.Infrastructure.Data.Context 

public class SqlServerContext :   IdentityDbContext<ApplicationUser> 

    public DbSet<Country> Country { get; set; } 

    public SqlServerContext(DbContextOptions<SqlServerContext> options) : base(options) 
    { 
      
    }     
    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
        base.OnModelCreating(modelBuilder); 
        modelBuilder.Entity<Country>(new CountryMap().Configure); 
        // ModelBuilderExtensions.Seed(modelBuilder); 

    } 

//Data for first time on table 
public static class ModelBuilderExtensions 

    public static void Seed(this ModelBuilder modelBuilder) 
    { 
        modelBuilder.Entity<Country>().HasData( 
            new Country 
            { 
                Id = 1, 
                Name = "Venezuela", 
                Population = 300000000, 
                Area = 230103 
              
            }, 
            new Country 
            { 
                Id = 2, 
                Name = "Peru", 
                Population = 260000000, 
                Area =33249               
            } 
        ); 
    } 


In the folder, EntityDbMapping, we create the CountryMap class. In this class, we define the physical representation of the properties of the Country class as fields in the table of the database.

    using Microsoft.EntityFrameworkCore;   
    using Microsoft.EntityFrameworkCore.Metadata.Builders;   
    using WebApi.Domain.Entities;   
       
    namespace WebApi.Infrastructure.Data.EntityDbMapping   
    {   
        public class CountryMap : IEntityTypeConfiguration<Country>   
        {   
            public void Configure(EntityTypeBuilder<Country> builder)   
            {   
                builder.ToTable("Country");   
       
                builder.HasKey(c => c.Id);   
       
                builder.Property(c => c.Name)   
                    .IsRequired()   
                    .HasColumnName("Name")   
                    .HasColumnType("varchar(150)");   
       
                builder.Property(c => c.Population)   
                    .IsRequired()   
                    .HasColumnType("int")   
                    .HasColumnName("Population");   
       
                builder.Property(c => c.Area)   
                    .IsRequired()   
                    .HasColumnType("decimal(14,2)")   
                    .HasColumnName("Area");   
       
                builder.Property(c => c.ISO3166)   
                .IsRequired()   
                .HasColumnType("varchar(3)")   
                .HasColumnName("ISO3166");   
       
                builder.Property(c => c.DrivingSide)   
                .IsRequired()   
                .HasColumnType("varchar(50)")   
                .HasColumnName("DrivingSide");   
       
                builder.Property(c => c.Capital)   
                .IsRequired()   
                .HasColumnType("varchar(50)")   
                .HasColumnName("Capital");   
            }   
       
        }   
    }   


This is it for now.
In the next chapter, we will implement validations with FluentValidation. We will also configure Mapper to use it with our DTOs and will implement Identity using Jwt.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in