0% found this document useful (0 votes)
296 views108 pages

Core Tutorial

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 108

Learn ASP.

NET Core Online


ASP.NET Core is a cross-platform, open-source framework for
building cloud-based web applications. ASP.NET Core Framework
becoming more popular among developers for various reasons
If you are familiar with earlier version of Asp.net Code behind or
Asp.net MVC you may find Asp.net Core little easy, if not, nothing to
worry, Let’s learn ASP.NET Core step by step

What's new in ASP.NET Core?


 Cross-platform & Container
Now we can create ASP.NET applications & deploy them to
Linux, macOS and Windows. Microsoft community have put
a huge effort into making Linux a first-class citizen for
running ASP.NET.
ASP.NET Core allows developers to utilize all of new
(containers) technologies like  Docker , Kuberenetes
 Unified MVC & Web API frameworks
 Multiple environments and development mode
 Dependency Injection
 WebSockets & SignalR
 Asynchronous via async/await
Ths is one of the reasons why ASP.NET Core is faster is its
extensive use of asynchronous patterns within the new
MVC Framework and Kestrel frameworks.
 Cross-Site Request Forgery (CSRF) Protection
 High performance
Here are few important features of Asp.net Core  you must know.

Asp.net Core Pre-requisites


 Prior knowledge of HTML and C# is mandatory.
 Understanding of ASP.NET WebForms or ASP.NET Mvc will
help to understand Asp.Net Core better (but not
mandatory)
 Should have some working knowledge of LINQ, Entity
Framework and SQL Server for database related
operations.
Download ASP.NET Core IDE
To start with Asp.net Core, First download the IDE, in google just
type "visual studio community", there you get  free version of visual
studio to downlaod  and practice

Learn Asp.Net Core with C# Examples


In this Asp.net Core Tutorial you will learn different controls of
Asp.net core, and how to develop web application using Asp.net core
framework with many real-time examples, also some best practices
that software development companies ask during  Asp.Net core
interview
 .Net Core Introduction
 Sample Project
 Appsettings.json
 .Net Core Program.cs
 .Net Core WwwRoot
 Asp.Net Core Middleware
 Kestrel web server
 .Net Core Startup.cs
 Asp.net Core Pages
 Partial Pages Razor
 Razor Page Methods
 Form in Razor Pages
 Asp.net Core Validation Technique
 Remote Validation in Asp.net Core
 Asp.net Core MVC
 Sesion in Asp.Net Core
 Bundleconfig.json
 Attribute Routing in Asp.net Core
 Asp.net Core CRUD Operations
 Exception Handling in Asp.net Core
 Logging in .Net Core
 Multiple Files Upload in Asp.Net Core MVC
 Retrieve static files / images from wwwroot folder
 Microservices in .Net Core
 Globalization Localization

Create Razor Pages Application

Learn Razor Pages in Asp.net Core


In this tutorial we will learn how to create a simple Asp.net Core
Web Application step by step to understand over all structure of
asp.net core project folders, pages, wwwroot, code behind etc.

Setp 1:
Open Visual Studio 2017, Select File => New => Project

Step 2:
Select "Web Application" then click "OK"
Step 3:
As we can see the following Asp.Net Core default stricture created
by visual studio. Now let’s understand each folder, files and how
they work.

Razor Page Application Structure


Now if you notice there is something called “Pages” folder which
contain many razor pages inside, razor pages are just like web form
in earlier version, so in this new pages we have chtml.cs , means
code behind file like we used to have in aspx.cs
The thought behind this razor page was to keep all functionalities
keep in one place for that particular page, so for small project or
website this may be good, but I personally don’t like the idea,
because for many reason, one strong reason is that this approach
may make “re-usability of code” more difficult, and writing all in one
place may look dirty.
While creating a page under pages folder, it gives an option to
select a model and one of CRUD operation.
But there was a plan for this type page design,  razor page is
lightweight, very flexible & cross platform compatible.
In next tutorial we talk about  handler methods and lifecycle of razor
page request in Asp.Net Core application.
Here are the few things like default files, folders you may find new
in asp.net development
 “wwwroot” for creating static file
 appSettings.json a json file
 Program.Cs
 bundleconfig.json for bundling and minification
 Startup.Cs etc.
so let’s learn them one by one.

wwwroot directory in Asp.net Core

what is wwwroot folder in asp.net core?


When we create any Asp.Net Core project, the wwwroot folder is
created by default, this folder is basically for all types of static files
like html, css, js, images etc.

Any other type of ASP.NET applications we can store any static files
in root, or in any other folder under root, and can be served from
there. This has been changed in ASP.NET Core. Now we can store
any static files under wwwroot folder only, all other files are blocked
on http request.
Appsettings.json in ASP.NET Core

How to use Appsettings.json?


Now you may not find any web.config file in Asp.net Core
application, but to keep all standard configuration information like
database connection string, SMTP information or any other custom
configuration you may need to keep, now all will go in a file called
Appsettings.json, but you still can continue with custom
configuration framework if you have already used in your
application.
How to add new keys in Appsettings.json?
Appsettings.json always contain values with key value pair separated
with a colon like “Key”: “Value”

Now for each key you can have a single value or multiple values with
a set of keys. you can write this way  “section-key” :{ “key1”:”value1”,
“key2”:”value2”}

How to read values from Appsettings.json file?


There are multiple ways to read value from Appsettings.json file
First we learn simple way, like how we used to read value from
web.config appsettings section.
In Asp.net Core we need to refer a
namespace Microsoft.Extensions.Configuration;  and then use
IConfiguration to read the value from appsettings.json file.
In controller constructor we need to set the local IConfiguration
property this way.
private readonly IConfiguration config;
public studentController(IConfiguration configuration)
{
config = configuration;
}

Here is the code


using Microsoft.Extensions.Configuration;
public class studentController : Controller
{
private readonly IConfiguration config;
public studentController(IConfiguration configuration)
{
config = configuration;
}
public IActionResult index()
{
// Method 1 to read value
string _dbCon1 =
config.GetSection("DbConnectionConfig").GetSection("Databa
seName").Value;
// Method 2 to read value
string _dbCon2 =
config.GetValue<string>("DbConnectionConfig:DatabaseName")
;
return View();
}
}

Method 2
There is another we can read values using custom class from
appsettings.json, like how we used to read  using custom
configuration in earlier .net version
See this code Illustration
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

public class HomeController : Controller


{
private readonly DbConnection dbconfig;
public HomeController(IOptions<DbConnection> dbcon)
{
dbconfig = dbcon.Value;
}
}

Make sure you have registered the new section in ConfigureService


method of Stratup.Cs
services.Configure<DbConnection>(Configuration.GetSection("DbCon
nectionConfig"));
ConfigureService Method of Startup.Cs

How to use Program.cs in ASP.NET Core

What is Program.cs ?
Program.cs file is the entry point of the application. This will be executed

first when the application runs, there is a  public static void Main method,

Whatever code you write inside that method will be executed in that

same order, In asp.net core application we normally call all "hosting

related setting and startup.cs file methods" from that Main() method.

Can we run application without Program.cs file ?


No, it will give an build error, will not allow to run the application.

In ASP.NET Core there is a new way to build web host configuration.


Now we can set defaults of the web host configuration using
WebHost.CreateDefaultBuilder()

This is how the Program.cs file look like

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}

In public static void Main()  of Program class where we can create a
host for the web application, earlier tutorial we have explained
about asp.net core Startup.cs class
var host = new WebHostBuilder();
// Now
IWebHostBuilder host = WebHost.CreateDefaultBuilder(args)
//CreateDefaultBuilder is a static method now create the
new instance
// finally call
host.Run();

How to use bundleconfig in Asp.net Core

Bundleconfig in Asp.net Core


Bundling and minification in ASP.NET Core : In earlier version of
Asp.net we had a BundleConfig.cs file with a static RegisterBundles
method, where we could add any additional files for bundling and
minification, but in .net Core there is no BundleConfig.cs file,
instead there is a BundleConfig.json, a plain text file, which works
very differently.

When you create a new Asp.net Core project a  bundleconfig.json file


automatically added to project

This is how the default file look like


[
{
"outputFileName": "wwwroot/css/site.min.css",
"inputFiles": [
"wwwroot/css/site.css"
]
},
{
"outputFileName": "wwwroot/js/site.min.js",
"inputFiles": [
"wwwroot/js/site.js"
],
"minify": {
"enabled": true,
"renameLocals": true
},
"sourceMap": false
}
]

inputFiles : takes comma separated name of all the files, here is an


example how you can add multiple file in that array.
"inputFiles": [
"wwwroot/js/site.js",
"wwwroot/js/user.js",
"wwwroot/js/product.js",
]

External utility for bundling and minification in


Asp.Net Core
There are many tools for bundling and minification in ASP.NET Core,
There some tools are from open source technologies and some are
developed by Microsoft.

Here we show how to work with few of them

BundlerMinifier, WebOptimizer, Webpack, Gulp

 BundlerMinifier
BundlerMinifier is the first choice for ASP.NET Core
application for bundling and minification,  read more about
this Utility. It has following features
o Bundle CSS, JavaScript or HTML files into a single output

file
o Supports MSBuild for CI scenarios
o Supports Command line
o Minify individual or bundled CSS, JavaScript and HTML files

You can install BundlerMinifier.Core using NuGet.

 WebOptimizer WebOptimizer is an ASP.NET Core middleware


for bundling and minification of JavaScript, CSS files at
runtime
 // in configureServices() method
 services.AddWebOptimizer();

 // in Configure() method
 app.UseWebOptimizer();
app.UseStaticFiles();

install WebOptimizer.Core using NuGet

 Gulp
Gulp is a JavaScript task runner which can automate many
common tasks of a website like minification, checking js
errors, bundling of various js and CSS files, optimizes images
etc.
Here is a nice article on How to  Use Gulp in ASP.NET Core

Startup.cs in ASP.NET Core


What is Startup class in Asp.net Core?
Startup class or Startup.cs file is generated as part of the default
Asp.net Core template. Startup class is the entry point of
application. It configures the request pipeline that handles all
requests made to the application.
Startup.cs is used for configuration & Startup Class is mandatory in

Asp.net Core application

Can we rename the startup class to some other name?


Yes, Finally this Startup.cs is used in  Program class for hosting the
application, So renaming this class will not make any difference.

Startup Class Constructor & IConfiguration


Setting up IConfiguration in Startup constructor
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

In Startup file you can see an example of dependency injection


ConfigureServices Method in Startup.cs
In ConfigureService method we can configure any service in that
application, to do that all service to be added in IServiceCollection
For example you can see how below methods are added
services.AddMvc(); this was added by default
services.Configure<DbConnection>(Configuration.GetSection("DbCon
nectionConfig"));
public class Startup
{ // This method gets called by the runtime. Use this
method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();

services.Configure<DbConnection>(Configuration.GetSection("
DbConnectionConfig"));
}
}
In above example we are try to configure a DbConnectionConfig
class we read information from appSetting.json class, so we want
when service starts, all configuration information to be available in
custom configuration class
Configure Method in Startup.cs
This method gets called by the runtime. Use this method to
configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
DbConnectionString =
string.Format("Server={0};Database={1};
User ID={2};Password={3};Trusted_Connection=False;
MultipleActiveResultSets=true;",
Configuration["DbConnectionConfig:ServerName"],
Configuration["DbConnectionConfig:DatabaseName"],
Configuration["DbConnectionConfig:UserName"],
Configuration["DbConnectionConfig:Password"]);
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template:
"{controller=Home}/{action=Index}/{id?}");
});
}

Kestrel web server in Asp.Net Core


Asp.Net Core Kestrel web server configuration  tutorial for
beginners.

What is Kestrel Web Server?


Kestrel is open-source, event-driven, asynchronous I/O based web
server for hosting ASP.NET applications. it uses async I/O library
called libuv primarily was developed for node.js

When we create any Asp.Net Core Projects, the Asp.net Core


templates include  Kestrel web server  by default

Kestrel web server is included in the project as a Nuget


package Microsoft.AspNetCore.Server.Kestrel

Why Kestrel when there was IIS

If you have been developing Asp.net application for some long time,
then you may have a question what was the necessity of Kestrel
when there was well established web server IIS!

First reason is, IIS is limited to windows OS only, but now Asp.net
core was designed to be hosted on other platform like LINUX, Mac,
so there was a need for a web server that can run on different OS
apart from windows.

Kestrel provides much efficient request processing to Asp.Net Core


applications, which helps improving the application performance.

Kestrel Web server Characteristic


 Kestrel is cross-platform, runs in Windows, LINUX and Mac.
 Kestrel webserver can supports SSL
 Using Kestrel, we cannot have multiple applications
running on same port
 Kestrel is a very light weight webserver that does not have
every advanced features of webservers like IIS
 But Kestrel is much faster compare to IIS

How to use Kestrel Web server?


We can use Kestrel Webserver just by calling the method
UseKestrel() in host builder of Program file.
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseIISIntegration()
.UseStartup<startup>()
.Build();
}

Notice .UseKestrel() method in above static BuildWebHost method,


Specify Kestrel server to be used by web host. that's how kestrel
server is configured in an Asp.Net Core application.

How to start Asp.Net Core app with Kestrel


In asp.net core application when we press F5 to run the application
on local machine, it uses “IISExpress” as web server, if you want to
use Kestrel web server to run your application on local machine, you
just need to click on drop-arrow icon next to “IISExpress” , then
select the application name, see the picture below.

Now if you click on F5, your Kestrel web server will start, and your
web page will open up in default browser.
You will see a black DOS window will open up, the window will
display all hosting related information.
If you want to shut down the Kestrel web server, you can either
close the window or press "control + C" to shut down.

Run using Dotnet CLI


You also can run the application from command prompt, just to open
command window and then run the following command.

dotnet run

Before running the above command make you go to project folder


location in your DOS window.
What is Razor Page in Asp.net Core?
Razor Page (chtml.cs) in Asp.Net Core is just like Aspx.cs in earlier
version of Asp.net, Razor Page is built on top of ASP.NET Core MVC,
but you don’t need any previous MVC knowledge, razor pages are
very light weight and easy to work with.

Create Razor Page


Right click on Page folder => Add => Razor Page=>
There you probably see three options Razor Page, Razor Page using
Entity Framework and Razor Page using Entity Framework (CRUD)
You can start with simple empty page.
 File name cannot start with underscore (_)
 File should have .cshtml extension
 First line in the file should be  @page
Here are few characteristic of Razor Pages in Asp.Net Core .
 ASP.NET Core Razor Pages is a page-centric framework for
building dynamic, data-driven web application.
 Razor Pages can support cross platform development and
easily can be deployed on different operating systems like
Windows, UNIX and Mac.
 The Razor Pages is very lightweight and flexible. It
provides full control over rendering HTML as per need,
easy to work with.
 The razor page framework is built on top of ASP.NET Core
MVC; anyone can work with asp.net core pages with having
any previous MVC Knowledge
 Every page has a Model, actually pages are inherited from
PageModel

Razor Page Models


A l l p a g e m o d e l a r e i n h e r i t e d f o r m   PageModel  c l a s s .
Add Property in Model
Notice every property in model has to have a  BindProperty attribute.
, then only you can access this property while form in submitted,
BindProperty is new in Asp.net Core, was not there in earlier
version.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RazorPages.Pages
{
public class IndexModel : PageModel
{
[BindProperty]
public string Email { get; set; }
}
}

This is how we call the model reference in chtml page


@page
@model IndexModel
@{
ViewData["Title"]="Page Title Here"
}

When you create razor page with model, a code behind file is
created
Example.cshtml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace LearnRazorPages.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
}

Working with Razor Page Forms


Example.cshtml: here is a simple form with three fields, the way we
used to write in classic asp, php etc
<form method="post">
<div>Name: <input name="name"/> </div>
<div>Name: <input name="email"/> </div>
<div>Name: <input name="mobile"/> </div>
<div> <input type="submit"/> </div>
</form>

Once you submit the form, you can access the submitted values in
your codebehind OnPost() method
Example.cshtml.cs:
public void OnPost()
{
var name = Request.Form["name"];
var email = Request.Form["email"];
var mobile = Request.Form["mobile"];
// now you have all submitted values in local variables
}

You should also read the Form in Razor Page to know more about
PageModel, Handler Methods, Leveraging Model Binding, Handler
method parameters etc.

Partial view in Asp.net Core Razor Page

Asp.net Core Razor Partial Page


Partial view is just like a razor page file, some people call it partial
page, only difference that partial view can be a part of main page,
we can write html and server side code in partial view, in one page
we can have any number of partial views.

Add partial view in razor page


You can create a partial view under Pages folder or in any other sub
folder.
Here we have created a partial view called "_menu" under
pages=>shared folder.
In above example we have created a simple partial view where we
want to add all common menu items
Remember Partial view doesn't have an @page directive at the top
File Name: _menu
<div>
Link 1 | Link 2 | Link 3 | Link 4
</div>

Now calling this partial view from any razor page


@Html.Partial("shared/_menu")
In Asp.Net Core 2.1 there is new partial tag helper.
The name attribute takes the name of partial file, with or without
the file extension, it works both ways
<partial name="shared/_menu" />

Html helper also offers 3 other methods for implementing partial


view, RenderPartial , RenderPartialAsync and PartialAsync
@{ Html.RenderPartial("shared/_menu"); }

Partial Pages Location and Naming Convention


There is no rule for partial view location and naming convention, you
can give any name, but as a standard practice we usually use
underscore at beginning for all naming partial view name, for
example you can see the above partial view name is "_menu".

Where to create the file?


You can create partial view in anywhere under “Pages”, But the best
practice would be to create a folder with name “shared” or “partial”,
then create all partial view under that folder.
There is also an advantage of keeping all partial views under one
folder; you can configure the location in  ConfigureServices method
under startup.cs file.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddRazorOptions(options =>
{
options.PageViewLocationFormats
.Add("/Pages/shared/{0}.cshtml");
});
}

Now while accessing the partial view, you don’t need to provide the
full path like @Html.Partial("shared/_menu"), you can
call @Html.Partial("_menu"), Automatically razor page view engine
will search that particular folder for all views

Razor pages partial view with model example


We can use model with partial view in asp.net core razor page ,
Here we learn how to work with strongly type partial view (with
model) in asp.net core razor page application.
In this example we have created following items
 One content razor page called "about.chtml" with
AboutModel:PageModel about.chtml.cs
 One partial view "_studentQuery" with a form to capture
student data
 One model class called student
Now we see how to use student model in partial view _studentQuery
then call that partial view from main page about.chtml
Step 1:
Create Student Model class with few properties
public class Student
{
public string Name { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
}

Step 2:
Create partial view with name "_studentQuery", then add the model
reference, and create a simple form to capture student data.
@model AspNetCoreWebApplication.Models.Student;
<form method="post">
Name: <input asp-for="Name" />
Mobile: <input asp-for="Mobile" />
Email: <input asp-for="Email" />
<input type="submit" value="Join" />
</form>

Step 3:
Now create the main content page about.chtml , and call the partial
view with model reference like @Html.Partial("_studentQuery",
model:Model.Student)
@page
@model AboutModel
@Html.Partial("_studentQuery", model:Model.Student)

Notice in above code, Model.Student is actually AboutModel.Student


So we need to create a property of Student type in AboutModel class
Step 4:
In About.chtml.cs file capture the submitted data
public class AboutModel : PageModel
{
public Student Student { get; set; }

public void OnGet()


{
Message = "Your application description
page.";
}
public void OnPost()
{
string _email = Request.Form["Email"];
}
}

Hope you understood how to use strongly type partial view in


asp.net core razor page

Razor Page Methods in Asp.Net Core


In our earlier Tutorial we have explained how to  create a Razor Page
project step by step. So now talk about handler method and Async
methods in asp.net core razor page.

Asp.Net Core Razor Page has some methods that are automatically
executed whenever we make a Request . There is some naming
convention used by Razor Pages framework, which helps to select
the appropriate handler method to execute.

Handler Methods in Razor Pages


Here are some standard methods of razor page codebehind [chtml.cs]

public void OnGet()


{
Message = "OnGet()";
}

public void OnPost()


{
Message = "OnPost()";
}
public void OnPut()
{
Message = "OnPut()";
}

Above methods are always executed when we request the page, All
method name follows standard naming convention.

Default Naming Convention


default convention of page methods (that are automatically executed
on page request)
"On" + HTTP verb used for the request

So all verbs are prefixed with "On" are the default methods name,
Like OnGet(), OnPost(), OnPut(), OnDelete() etc.
All Handler methods in razor page also have optional asynchronous
equivalents method like OnGetAsync(), OnPostAsync() etc. Now you
do not need to add the Async suffix

You can have either of these two methods in same razor page codebehind

[chtml.cs]

public void OnGet()


{
Message = "OnGet()";
}
Or
public void OnGetAsync()
{
Message = "OnGetAsync()";
}

Writing both will throw “InvalidOperationException: Multiple handlers


matched” exception, because both handlers are same, one with
Async one without.

Note: even if one method takes parameter and other one without
parameter still same exception will be thrown, means if you have
OnGet(string parameter1) and OnGetAsync() still won’t work, it’s
still considered as multiple handlers on same page.

Custom method in Razor Page Asp.net Core


So far we have seen how to deal with standard methods, now we
learn how to write custom method in asp.net core razor page.

We can give any name to method as per our business requirement


Let's assume we need to create a registration form for company's
annual function, here we create a simple registration form
<form method="post">
Name: <input type="text" name="FullName" />
<button asp-page-handler="Register">Register</button>
</form>

Now in code behind we have to write a custom method to capture


the data, for method name we have to follow some naming
convention, method name always has to be like "OnPost" + asp-
page-handler value.
So here name should be OnPost + Register= OnPostRegister()
public void OnPostRegister()
{
var name = Request.Form["FullName"];
// now you have all submitted values in local variables
}

We also can make Async method


"OnPost" + asp-page-handler value + Async
public void OnPostRegisterAsync()
{
var name = Request.Form["FullName"];
// now you have all submitted values in local variables
}

But remember we can't have both methods on same page, even with
different signature, then that will throw an exception for multiple
handlers.

Handling Multiple Submit Buttons In Razor Pages


Now learn how to deal with multiple submit button with real time
example
Here we have designed a simple form; we want to capture the
training request from our employees, who want to learn which
subject! (You probably thinking this could have been done different
ways, true! this just to give an example of multiple submits!)
<form method="post">
<input type="submit" value="Asp.net" asp-page-
handler="Aspnet" asp-route-valuecount="10" />
<input type="submit" value="Asp.net MVC" asp-page-
handler="Aspnetmvc" asp-route-valuecount="12"/>
<input type="submit" value="Asp.net Core" asp-page-
handler="Aspnetcore" asp-route-valuecount="15"/>
<input type="submit" value="LINQ" asp-page-handler="Linq"
asp-route-valuecount="20"/>
<input type="submit" value="HTML" asp-page-handler="Html"
asp-route-valuecount="10"/>
</form>

Now in code behind you can write multiple handler method, each
time form is submitted a different method is getting executed, so
based method you can update database, write complex business logic
to decide further action for user.
public void OnPostAspnet(int valuecount)
{
ViewData["ActionMessage"] = $"Aspnet
{valuecount}";
}
public void OnPostAspnetmvc(int valuecount)
{
ViewData["ActionMessage"] = $"AspnetMVC
{valuecount}";
}
public void OnPostAspnetcore(int valuecount)
{
ViewData["ActionMessage"] = $"AspnetCore
{valuecount}";
}
public void OnPostLinq(int valuecount)
{
ViewData["ActionMessage"] = $"LINQ
{valuecount}";
}
public void OnPostHtml(int valuecount)
{
ViewData["ActionMessage"] = $"Html
{valuecount}";
}

Please make sure method naming convention is followed.

Asp.Net Core Razor Page Form Example


Now we learn about How to work with Form in Asp.Net Razor Pages,
PageModel, Handler Methods, Leveraging Model Binding, Handler
method parameters etc.

Create Form in Razor Page


In razor page we can create form in two ways

1. Using simple html form tag


2. Using MVC form syntax
With both type of form tag we can work using model and non-
model.
Here we learn both form tag and with & without Model

Razor Page Form without Model Example


Example 1 .cshtml: here is a simple  html form tag without
Model with three fields, the way we used to write in classic asp,
php etc
<form method="post">
<div>Name: <input name="FullName" /> </div>
<div>Email: <input name="Email" /> </div>
<div>Mobile: <input name="ContactNumbers" /> </div>
<div> <input type="submit" /> </div>
</form>

Example 2 .cshtml: here is an example  Using MVC form without


Model syntax with three fields.
@using (Html.BeginForm(FormMethod.Post))
{
<div class="s1">
<div>Full Name</div>
@Html.TextBox("FullName", new { @class = "searchTxt" })
</div>
<div class="s1">
<div>Contact Numbers</div>
@Html.TextBox("ContactNumbers", new { @class =
"searchTxt"})
</div>
<div class="s1">
<div>Email</div>
@Html.TextBox("Email", new { @class = "searchTxt" })
</div>
<div>
<input type="submit" value="Contact" />
</div>
}
Razor Page Form with Model Example
Create Model for Razor Form
First we create a simple Model with few properties , each property
has to have a [BindProperty] attribute
public class ContactModel : PageModel
{
[BindProperty]
public string FullName { get; set; }
[BindProperty]
public string ContactNumbers { get; set; }
[BindProperty]
public string Email { get; set; }
}

Example 1 .cshtml:
here is a simple example of  html form tag with Model  with three
fields.

Now if you notice I have specified fields in two different ways, first
one Using MVC style and other one using asp-for="propertyname",
both works fine!
<form method="post">
<div>@Html.TextBoxFor(m => m.FullName)</div>
<div>Email: <input asp-for="Email" /> </div>
<div>Mobile: <input asp-for="ContactNumbers" /> </div>
<div> <input type="submit" /> </div>
</form>

Example 2 .cshtml:
Using MVC form syntax with three fields
@using (Html.BeginForm(FormMethod.Post))
{
<div class="s1">
<div>Full Name</div>
@Html.TextBoxFor(m => m.FullName) </div>
<div class="s1">
<div>Contact Numbers</div>
@Html.TextBoxFor(m => m.ContactNumbers) </div>
<div class="s1">
<div>Email</div>
@Html.TextBoxFor(m => m.Email)
</div>
<div>
<input type="submit" value="Contact" />
</div>
}

Razor Form Submission


Once you submit the form, you can access the submitted values in
your codebehind OnPost() method
Now here we have given two examples
This one will work only if you have Model associated with the form

Example.cshtml.cs:

public void OnPost()


{
var name = FullName;
var email = Email;
var mobile = ContactNumbers;
// now you have all submitted values in local variables
}

This example will work in both situations, with Model and without
Model
Still you can access properties using Request.Form["fieldName"]
public void OnPost()
{
var name = Request.Form["FullName"];
var email = Request.Form["Email"];
var mobile = Request.Form["ContactNumbers"];
// now you have all submitted values in local variables
}

Handling Multiple Actions For Form in Razor Page


In some situation you may need to have multiple action buttons, in
such situation you can write separate named handler methods, and
in action tag helper specify the handler method name.
<form method="post">
<button asp-page-handler="Register">Register</button>
<button asp-page-handler="Request">Request Info</button>
</form>

Now in codebehind specify the method name with OnPost Prefix or


Async Suffix
public void OnPostRegister()
{
var name = Request.Form["FullName"];
// now you have all submitted values in local variables
}
public void OnPostRequest()
{
var name = Request.Form["FullName"];
// now you have all submitted values in local variables
}

Now if you notice above methods name "OnPost" + value of asp-page-

handler

You should also read razor pages handler methods in Asp.Net Core

Asp.net Core validation Example


Asp.net Core Validation Tutorial for beginners step by step

Asp.net Core Razor validation Technique


When you accept data input from user then save the data in
database, you must ensure that all incoming values that user has
entered, are matching with data type, length specified in database,
otherwise that will produce error and won’t be able to save the data
in database.

So, you have to validate before processing data.

There are differ ways you can validate data in Asp.net Razor Form
Razor page framework are built on MVC Framework, so it supports
following input validation framework.

 Validation using DataAnnotation Attributes


 Vlidation using Tag Helpers
 jQuery Unobtrusive Validation
 Server Side Validation Technique

Model Validation using DataAnnotation Attributes


Validation using DataAnnotation Attributes in Asp.Net Core works in
the same way we used to perform  validation in earlier Asp.net MVC .
All validation classes are inherited from  ValidationAttribute, You
need to use System.ComponentModel.DataAnnotations  Namespace

Validation Attributes in Asp.net Core


 Required
Indicates that the value must be provided for this field,
else display error message

 Range
Specify the minimum and maximum values of a range, so
user must provide a value within that range

 Compare
Compare the value of two fields, or with a fixed specified
value

 StringLength
Sets the maximum number of string characters allowed

 MaxLength
Sets the maximum length, number of characters can be
accepted

 MinLength
Sets the minimum length, number of characters can be
accepted

 RegularExpression
Checks if the value matching against the specified regular
expression

 Remote
It helps enabling client-side validation against a server-
side code, like checking database to see if a partial email
id is already in use

Client side validation in Razor Asp.net Core


In form you also can provide client side validation support using
jQuery.
Here we design a simple form to show how to display
<form method="post">
<input asp-for="FullName" />
<span asp-validation-for="FullName"></span>
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
<input asp-for="ContactNumbers" />
<span asp-validation-for="ContactNumbers"></span>
<input type="submit" value="Submit" />
</form>

If you check how the html look like after rendering, notice  data-
val="true", if set data-val="false" then validation won't happen
<form method="post">
Name:<input type="text" data-val="true" data-val-length="5-
60 character" data-val-length-max="60" data-val-length-
min="5" data-val-required="Full Name Required"
id="FullName" name="FullName" value="" />
<span class="field-validation-valid" data-valmsg-
for="FullName" data-valmsg-replace="true"></span>

Email: <input type="email" data-val="true" data-val-


email="Invalid email" data-val-required="Email required"
id="Email" name="Email" value="" />
<span class="field-validation-valid" data-valmsg-
for="Email" data-valmsg-replace="true"></span>

Mobile: <input type="text" data-val="true" data-val-


length="10-14 character" data-val-length-max="14" data-val-
length-min="10" data-val-required="Contact Numbers
Required" id="ContactNumbers" name="ContactNumbers"
value="" />
</form>

Make sure you have added following jquery files as reference in your
page

@section scripts
{
<script src="~/lib/jquery.js"></script>
<script src="~/lib/jquery.validate.js"></script>
<script src="~/lib/jquery.validate.unobtrusive.js"></script>
}

Asp.net Core Model Validation Example


Server side validation: Sometimes it’s necessary to implement
server side validation, because we cannot depend on client side
validation completely, there are ways to disable client side script,
sometimes they are not supported by different version of different
browsers, sometimes bugs can cause problem, so in framework there
is also an easy way to check server side validation.
public class ContactModel : PageModel
{
[Required(ErrorMessage = "Full Name Required")]
[StringLength(60, ErrorMessage = "5-60 character",
MinimumLength = 5)]
[BindProperty]
public string FullName { get; set; }
[Required(ErrorMessage = "Contact Numbers
Required")]
[StringLength(14, ErrorMessage = "10-14 character",
MinimumLength = 10)]
[BindProperty]
public string ContactNumbers { get; set; }
[EmailAddress(ErrorMessage = "Invalid email")]
[Required(ErrorMessage = "Email required")]
[BindProperty]
public string Email { get; set; }
public void OnGet()
{
Message = "Your application description page.";
}
public void OnPost()
{
string _email = Request.Form["Email"];
}
}

In every PageModel validation error is added to


ModelStateDictionary, and you can access the dictionary result using
ModelState of PageModel class.

ModelState has a property called IsValid, which indicates if


validation check is successful, if not the IsValid property become
false.

Here is how you can check the validation at server side


public IActionResult OnPost()
{
if (ModelState.IsValid)
{
// add data in database
var fullName = FullName;
var contactNumbers = ContactNumbers;
var email = Email;
// then redirect to success page
}
else
{
// redirect to validation page
}
}

Asp.net Core Remote Validation Example


Remote validation is basically validating data with database or any
other external web services while user entering data in text box,
making an ajax call to server side code to check if the input is valid
or else display the error message immediately.

Here I have written an example of  Remote Validation Implementation


in Asp.net Core

Remote validation in Asp.net Core Razor Pages


What is Remote validation in Asp.net Core?

Remote validation is a technique of validating data with database or any

other external web services while user entering data in text box, making

an ajax call to server side code to check if the input is valid or else

display the error message immediately


Remote validation example in asp.net core
step by step
Story behind implementation

We have created a simple form for accepting student registration for

sports event, so apart from student name and mobile number we are also

accepting a unique code as their choice, but we need to validate the code

with backend server to ensure that the same code has not been taken by

some other student. , and we have to check that at the time of

registration only.

Step 1:

Create a form with following fields like FirstName, LastName, Email

and StudentCode, StudentCode is the field where we experiment Remote

validation.

<form asp-controller="student" asp-action="index"


method="post"> <div asp-validation-summary="ModelOnly"
class="text-danger"> </div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"> </label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger">
</span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"> </label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger">
</span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"> </label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger">
</span>
</div>
<div class="form-group">
<label asp-for="StudentCode" class="control-label">
</label>
<input asp-for="StudentCode" class="form-control" />
<span asp-validation-for="StudentCode" class="text-
danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save Student"
class="btn btn-default" />
</div>
</form>

Step 2:
Make sure you have added following jquery file reference, so that
ajax request works properly
@section scripts
{
<script src="~/lib/jquery.js"></script>
<script src="~/lib/jquery.validate.js"> </script>
<script src="~/lib/jquery.validate.unobtrusive.js">
</script>
}

Step 3:
Now we create the model with all above fields, and notice how we are

setting Remote attribute on StudentCode property

public class StudentModel


{
public int StudentId { get; set; }
[Required(ErrorMessage = "Firstname Required")]
[StringLength(50, ErrorMessage = "5 to 50 characters.",
MinimumLength = 3)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Lastname Required")]
[StringLength(50, ErrorMessage = "5 to 50 characters.",
MinimumLength = 3)]
public string LastName { get; set; }
[Required(ErrorMessage = "Email Required")]
[EmailAddress(ErrorMessage = "Invalid email")]
public string Email { get; set; }
[Required(ErrorMessage = "Code Required")]
[Remote("ValidateCode","student", ErrorMessage = "Please
enter a valid code")]
public string StudentCode { get; set; }
}

This is how you call the method with Remote attribute

[Remote("MethodName","ControllerName", ErrorMessage = "Error

Message")]

Step 4:
Now we write the method in server side code to interact with
database or any external web service, this is the place where we
check if the code is already exist in database
public IActionResult ValidateCode(string code)
{
string result;
// here you can check the code with database
if (code == "wtr1")
{
result = "Valid code";
}
else
{
result = "Invalid code";
}
return Json(result);
}

Note:
Here we have not connected with database or web service, we simply
checked with a hardcoded value “wtr1”, you can replace that code
with your database call or web service call

ASP.NET Core MVC Project with Database


Example
Asp.Net Core MVC for Beginners Step by Step, in this tutorial we
learn how to develop Model View Controller Application using
Asp.net Core Framework.

Before you learn MVC in Asp.Net Core, We suggest you to have good
understanding about Model View Controller in Asp.net , because in
this article we talk about only what we implement differently in
Asp.net Core.
Here are the steps we perform to create an Asp.Net Core MVC
application with Entity Framework Core  as Data Access Layer

 Create an Asp.Net Core MVC Application


 Create new Controller for Student
 Model for Student with property Validation
 A Razor View for Student, where we can add new student
and display the list
 A new Entity for Student and a Table in database
 Implement Code First approach in Entity Framework
 Finally Create new student and display them all on screen

Creating Asp.Net Core MVC Project Step by


Step
Open Visual Studio 2017 and above then select new project, under
"Web" select ".Net Core"
Now there are different types of Asp.net Core Web Application, Select
Model View Controller

Basic structure of Asp.Net Core MVC Application, here we set up student


model, view and controller
Model, View, Controller in Asp.Net Core
Model We create a new model for Student, we name it StudentModel
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace AspNetCoreMVC.Models
{
public class StudentModel
{
[Required(ErrorMessage = "Firstname Required")]
[StringLength(50, ErrorMessage = "5 to 50
characters.", MinimumLength = 3)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Lastname Required")]
[StringLength(50, ErrorMessage = "5 to 50
characters.", MinimumLength = 3)]
public string LastName { get; set; }
[Required(ErrorMessage = "Email Required")]
[EmailAddress(ErrorMessage = "Invalid email")]
public string Email { get; set; }
public string Mobile { get; set; }
public List<Student> Students { get; set; }
}
}

View
Now we design view (razor) where we want to capture new student
data and display the student list.
Here are some important tags for designing form in Asp.Net Core
Razor.
Please notice how syntax is different than earlier  Asp.net MVC

Form design in Asp.Net Core Razor Syntax

Controller <form asp-controller="controllerName"/>

Action <form asp-action="actionName"/>

Method <form method="post"/>

Field <input asp-for="fieldName" />

Validation Message <span asp-validation-for="fieldName" />

Submit Button <input type="submit" />


Controller
In case you need to read any type of configuration information from
appsettings.json file, this is how you can get the configuration
information in controller.
Also there is another way to read the configuration
from appsettings.json information into DbContext
Here we create a new controller, where we can add a new student
and display the list of student
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using AspNetCoreMVC.Models;
using AspNetCoreMVC.DTO;
/// <summary>
/// Written by WebTrainingRoom.Com
/// </summary>
namespace AspNetCoreMVC.Controllers
{
public class studentController : Controller
{
private readonly IConfiguration config;
public studentController(IConfiguration
configuration)
{
config = configuration;
}
[HttpPost]
public IActionResult index(StudentModel model)
{
Student _student = new Student();
_student.Firstname = model.FirstName;
_student.Lastname = model.LastName;
_student.ContactNumber = model.Mobile;
_student.Email = model.Email;

using (StudentDTO dto = new StudentDTO())


{
dto.AddStudent(_student);
}
return RedirectToAction("index", new { msg =
"New Student Added" });
}
[HttpGet]
public IActionResult index()
{
StudentModel model = new StudentModel();

using (StudentDTO dto = new StudentDTO())


{
model.Students = dto.GetAllStudents();
}
return View(model);
}
}
}

Work with Database in Asp.net Core MVC


As we mentioned earlier in this example we will use  Entity
Framework Core as Data Access Layer, So from our Data Transfer
Class we will call the instance of  Entity DbContext Class.
Here is how our DataTransferObject called "StudentDTO" will look
like, learn about DbContext class  EFContext() in entity framework
Core
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Written by WebTrainingRoom.Com
/// </summary>
namespace AspNetCoreMVC.DTO
{
public class StudentDTO
{
public Student AddStudent(Student s)
{
using (EFContext context = new EFContext())
{
context.tbStudent.Add(s);
context.SaveChanges();
}
return s;
}
public List<Student> GetAllStudents()
{
List<Student> list = new List<Student>();
var context = new EFContext();
list = context.tbStudent
.ToList<Student>();

return list;
}

}
}

How to use Session in Asp.net Core


What is session in Asp.net ?
Session management in asp.net is a technique to store and retrieve
information from session object , we normally store user specific
data in session object , so one user login we can use those
information in different pages where user keep browsing , we can
get those information from session object without going to database
every time

How to use session in Asp.net Core


If you have experience in working with earlier asp.net version, you
must have worked with session object, but in asp.net core
implementation of session object is little different than earlier
version, in earlier asp.net we could straight away store and retrieve
any type of information from session just by using key-value

But in asp.net core you have to do some additional work to use


session object in application, you have to add session in middleware
pipeline
Step 1
Open startup.cs file and inside ConfigureServices method register
the AddSession() method
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
}

Step 2
Now in Configure method call UseSession() method
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseSession();
}

Step 3
Now install Microsoft.AspNetCore.Session  utility from Nugget

Setting and retrieving values in Asp.net Core Session object

In ASP.NET Core Session object there are 3 methods to set the


session value, which are Set, SetInt32 and SetString.
HttpContext.Session.SetString("sessionKeyString",
"WebTrainingRoom");
HttpContext.Session.SetInt32("sessionKeyInt", 10);

And three methods for retrieving values from session , which are
Get, GetInt32 and GetString
string _sessionStringvalue =
HttpContext.Session.GetString("sessionKeyString");
int? _sessionIntValue =
HttpContext.Session.GetInt32("sessionKeyInt");
So far we have seen how to use session object to store simple
information, but there is no straight way to store complex object in
asp.net core session.
Now we learn how to store complex object in session

How to store complex object in Asp.net core session


So we have already understood there is no straight way of storing
complex data in session like we used to do in earlier asp.net version,
but here is how we can store complex data in asp.net core session

We have to create an additional class to add any object current session

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
public static class SessionHelper
{
public static void SetObjectAsJson(this
ISession session, string key, object value)
{
session.SetString(key,
JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this
ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}
Now let's call the above methods to add and retrieve complex object
in session.
In following example we add a student object list in session and
retrieve from session

List<WtrStudent> _sList=new List<WtrStudent>();


SessionHelper.SetObjectAsJson(HttpContext.Session, "userObject",
_sList);
List<WtrStudent> _sessionList=
SessionHelper.GetObjectFromJson<List<WtrStudent>>(HttpContext.Sessi
on, "userObject");

Hope you understood how to work with  session in asp.net


core and storing complex object in asp.net core session

How to use bundleconfig in Asp.net Core

Bundleconfig in Asp.net Core


Bundling and minification in ASP.NET Core : In earlier version of
Asp.net we had a BundleConfig.cs file with a static RegisterBundles
method, where we could add any additional files for bundling and
minification, but in .net Core there is no BundleConfig.cs file,
instead there is a BundleConfig.json, a plain text file, which works
very differently.

When you create a new Asp.net Core project a  bundleconfig.json file


automatically added to project

This is how the default file look like


[
{
"outputFileName": "wwwroot/css/site.min.css",
"inputFiles": [
"wwwroot/css/site.css"
]
},
{
"outputFileName": "wwwroot/js/site.min.js",
"inputFiles": [
"wwwroot/js/site.js"
],
"minify": {
"enabled": true,
"renameLocals": true
},
"sourceMap": false
}
]

inputFiles : takes comma separated name of all the files, here is an


example how you can add multiple file in that array.
"inputFiles": [
"wwwroot/js/site.js",
"wwwroot/js/user.js",
"wwwroot/js/product.js",
]

External utility for bundling and minification in


Asp.Net Core
There are many tools for bundling and minification in ASP.NET Core,
There some tools are from open source technologies and some are
developed by Microsoft.
Here we show how to work with few of them

BundlerMinifier, WebOptimizer, Webpack, Gulp

 BundlerMinifier
BundlerMinifier is the first choice for ASP.NET Core
application for bundling and minification,  read more about
this Utility. It has following features
o Bundle CSS, JavaScript or HTML files into a single output

file
o Supports MSBuild for CI scenarios
o Supports Command line
o Minify individual or bundled CSS, JavaScript and HTML files

You can install BundlerMinifier.Core using NuGet.

 WebOptimizer WebOptimizer is an ASP.NET Core middleware


for bundling and minification of JavaScript, CSS files at
runtime
 // in configureServices() method
 services.AddWebOptimizer();

 // in Configure() method
 app.UseWebOptimizer();
app.UseStaticFiles();

install WebOptimizer.Core using NuGet

 Gulp
Gulp is a JavaScript task runner which can automate many
common tasks of a website like minification, checking js
errors, bundling of various js and CSS files, optimizes images
etc.
Here is a nice article on How to  Use Gulp in ASP.NET Core

Attribute Routing Example in Asp.net MVC

Attribute Routing in MVC C#


We have already explained routing concept in our earlier tutorial, if
you very new to routing concept then please read  routing in asp.net
mvc first. Attribute routing is conceptually same but technically
implemented differently; you can alternative approach to
conventional routing.

Why Attribute Routing Useful?


In earlier version Asp.net MVC we had a limitation of
defining SEO friendly Action Name, for example if we can have
action name as "attribute-routing" instead of "attributerouting" that
would be more appropriate for SEO.

How to Use Attribute Routing


Applying routing to any action using attribute is very simple!
Create a controller and an action, and then apply the attribute with
any SEO friendly name you want, notice how we have
applied [Route("attribute-routing")]  in below IActionResult
[Route("attribute-routing")]
public IActionResult attributerouting()
{
return View();
}
Now probably you need to make one more changes in your Configure
method of Startup.cs file.
So open the startup file and make the following changes

Instead of

app.UseMvcWithDefaultRoute();

Replace with following code

app.UseMvc(routes =>
{
routes.MapRoute(
name:"default",
template: "{controller=Home}/{action=Index}/{id?}");
});

Now you have successfully implemented Attribute Routing.


You can try accessing the page on browser by calling the attribute
value, like in this case controlloerName/attribute-routing

Razor Pages CRUD operations in Asp.net Core

CRUD in Razor Page Application


In this tutorial we will learn how to create, read, update, and delete
(CRUD) in asp.net core razor page application, so we learn how work
with database.

While working with database from razor pages you can use any data
access mechanism like Ado.Net, Entity Framework etc.

Here in example we will be using Entity Framework


Create a Asp.net Razor Page Project, then add a new page, here in
example we have created a page for student, we learn how to add
new student then read, edit and delete on the same page.

Step 1: Create a page and design a form


Notice, in form, there is hidden field called StudentId, this will help
to differentiate new and existing student
<form method="post">
@Html.HiddenFor(m => m.StudentId)
<div asp-validation-summary="ModelOnly" class="text-
danger"> </div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"> </label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-
danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName"
class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label">
</label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-
danger"> </span>
</div>
<div class="form-group">
<label asp-for="Mobile" class="control-label">
</label>
<input asp-for="Mobile" class="form-control" />
<span asp-validation-for="Mobile" class="text-
danger"> </span>
</div>
<div class="form-group">
<input type="submit" value="Save Student"
class="btn btn-default" />
</div>
</form>

Read Existing Students


@if (Model.Students != null)
{
foreach (Student s in Model.Students)
{
<div style="padding:5px;">
@s.Firstname @s.Lastname <a
href="@Url.Action("index","student",new
{ sid=s.StuId})">Edit</a> | <a
href="@Url.Action("delete","student",new
{ sid=s.StuId})">Delete</a>
</div>
}
}

Step 2:
Create database connection details in  appsettings.json and Entity
Framework class DbContext
"DbConnectionConfig": {
"DatabaseName": "MarketingDB",
"UserName": "masa",
"Password": "mapass",
"ServerName": "USER-PC"
}

Step 3:
Create a DTO class to interact with database using Entity
Framework, in this class we have written four methods AddStudent,
UpdateStudent, GetAllStudents, DeleteStudents,  Learn IDisposable
Implementation
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AspNetCoreWebApplication.DTO
{
public class StudentDTO : IDisposable
{
public Student AddStudent(Student s)
{
using (EFContext context = new EFContext())
{
context.tbStudent.Add(s);
context.SaveChanges();
}
return s;
}
public Student UpdateStudent(Student student)
{
Student _s = null;
using (EFContext context = new EFContext())
{
_s = context.tbStudent
.Where(s => s.StuId == student.StuId)
.FirstOrDefault<Student>();
if (_s != null)
{
_s.Firstname = student.Firstname;
_s.Lastname = student.Lastname;
_s.Email = student.Email;
_s.ContactNumber = student.ContactNumber;
context.SaveChanges();
}
}
return _s;
}
public List<Student> GetAllStudents()
{
List<Student> list = new List<Student>();
var context = new EFContext();
list = context.tbStudent
.ToList<Student>();
return list;
}
public bool DeleteStudent(int stuid)
{
bool _isDeleted = false;
Student _s = null;
var context = new EFContext();
_s = context.tbStudent
.Where(s => s.StuId == stuid)
.FirstOrDefault<Student>();
if (_s != null)
{
context.tbStudent.Remove(_s);
context.SaveChanges();
_isDeleted = true;
}
return _isDeleted;
}
public Student GetStudent(int sid)
{
Student _s = null;
using (EFContext context = new EFContext())
{
_s = context.tbStudent
.Where(s => s.StuId == sid)
.FirstOrDefault<Student>();
}
return _s;
}
}
}

Step 4:
In PageModel public class studentModel:PageModel {}

First we create model properties

[BindProperty]
public int StudentId { get; set; }
[BindProperty]
[Required(ErrorMessage = "Firstname Required")]
[StringLength(50, ErrorMessage = "5 to 50
characters.", MinimumLength = 3)]
public string FirstName { get; set; }
[BindProperty]
[Required(ErrorMessage = "Lastname Required")]
[StringLength(50, ErrorMessage = "5 to 50
characters.", MinimumLength = 3)]
public string LastName { get; set; }
[BindProperty]
[Required(ErrorMessage = "Email Required")]
[EmailAddress(ErrorMessage = "Invalid email")]
public string Email { get; set; }
[BindProperty]
public string Mobile { get; set; }
[BindProperty]
public List<Student> Students { get; set; }

Setup property values in OnGet() method

public void OnGet()


{
int _id = Convert.ToInt32(Request.Query["sid"]);
Student _s = null;
using (StudentDTO dto = new StudentDTO())
{
this.Students = dto.GetAllStudents();
_s = dto.GetStudent(_id);
if (_s != null)
{
this.StudentId = _s.StuId;
this.Email = _s.Email;
this.FirstName = _s.Firstname;
this.LastName = _s.Lastname;
this.Mobile = _s.ContactNumber;
}
}
}
Finally When form submitted, we capture the value and update database

in OnPost() method

public IActionResult OnPost()


{
Student _student = new Student();
_student.Firstname = FirstName;
_student.Lastname = LastName;
_student.ContactNumber = Mobile;
_student.Email = Email;
_student.StuId = StudentId;
using (StudentDTO dto = new StudentDTO())
{
if (_student.StuId == 0)
{
dto.AddStudent(_student);
}
else
{
dto.UpdateStudent(_student);
}
}
return RedirectToPage("student", new{msg="updated"});
}

I hope you understood how to add, select, edit, delete data in


asp.net razor page application

Exception handling in Asp.net Core

Asp.net Core Error handling Example


Exception handling is one of the very important feature in
application development life cycle, that help us to deal with the
unexpected errors which could appear from our coding, server
connectivity, bad data, or any other situation, so there are many
different ways for handling such exception

Now we learn exception handling in asp.net core .


If you have not read our earlier  exception handling in
asp.net tutorial, please read that, here we discuss different ways of
exception handling in asp.net core application only

Exception handling is also type of  Middleware in Asp.net Core

In this tutorial we will talk about three different ways of error


handling in Asp.net Core

 Error Handling with Try-Catch Block


 Global Errors Handling with UseExceptionHandler
Middleware
 Global Exception Handling with the Custom Middleware

Asp.net core catch all errors


Try catch is common in all most all development practice, very easily
can implemented on every function or method you write.

Error Handling with Try-Catch Block


try
{
// here you write you code
}
catch (Exception ex)
{
here you get all exception details in Exception
variable, you can either log the error details or display
to user
}
finally
{
// is optional
}

Global Errors Handling with Middleware


We use Exception handling middleware UseExceptionHandler in
Configure method of Startup.Cs
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
// write error handling code here
}

To understand if error handling is working properly let’s create some


error on PageModel class
public void OnGet()
{
throw new Exception("this is an exception");
}

The above code will throw error, will see how differently we can
catch the exception and log error details and display user friendly
error message .

asp.net core error development mode


We can implement different type of exception handling mechanism
for different environment like for development, staging, production
etc.
if(env.IsDevelopment() || env.IsStaging())
{
app.UseDeveloperExceptionPage();

}
else
app.UseExceptionHandler("/error");

Now in above exception handling technique you will be able redirect


user to a error page with some messages, but this will not help you
to capture actual error details for logging or resolving the issue.

So now let's look at another way of capturing error details

Use of UseExceptionHandler
app.UseExceptionHandler(
options =>
{
options.Run(
async context =>
{
context.Response.StatusCode =
(int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var ex =
context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var err = $"<h1>Error:
{ex.Error.Message}</h1>{ex.Error.StackTrace}";
await
context.Response.WriteAsync(err).ConfigureAwait(false);
}
});
}
);

Global Exception Handling with Custom Middleware

Now we see how to write a custom middleware for error handling,


and how to access current HttpContext and error details associated
with that
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace AspNetCoreWebApplication
{
public class WTRCustomMiddleware
{
private readonly RequestDelegate _next;
public WTRCustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await context.Response.WriteAsync("- Before Message - \n\
r");
await _next(context);
var ex = context.Features.Get<IExceptionHandlerFeature>();
await context.Response.WriteAsync("\n\r - After
Message - ");
}
}

Now create a Middleware Extensions class

public static class WTRCustomMiddlewareExtensions


{
public static IApplicationBuilder
UseWTRCustomMiddleware(this IApplicationBuilder builder)
{
return
builder.UseMiddleware<WTRCustomMiddleware>();
}
}
}

In above middleware you have HttpContext, so get the exception


details var ex =
context.Features.Get<IExceptionHandlerFeature>();  Now call the
above custom middleware in Configure method of Statup.cs
app.UseWTRCustomMiddleware();
app.Run(async context =>
{
await context.Response.WriteAsync("Welcome to
WebTrainingRoom!");
});

Now we see how to catch error status code like page not found,
internal server error etc.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseStatusCodePages();
}
Now if try to access some unknown page on browser, you will get
following error message

Status Code: 404; Not Found

Above method is good enough to catch error status code and display
the error, but in application development sometimes you may want
to display the error to a different user friendly page with other page
navigation, in such situation you can use
UseStatusCodePagesWithRedirects().
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseStatusCodePagesWithReExecute("/Error", "?
statusCode={0}");
}

this method will redirect user to a different error page, where you
can show custom error message based on statusCode, alternatively
you also can create different error page for each code, and redirect
to page based on code.

Logging example in Asp.net Core

Asp.net Core Logging Example


Logging is one of the very important functionalities in software
development, Asp.net Core Logging can be used for various reason,
but most of the time we use logging function for User Activity
logging and Error Logging, You can use logging anywhere you want.

In Asp.net Core we have built-in logging apart from third party


logging utility like Log4net. ASP.NET Core logging framework is not
as feature-rich as third party libraries, So let’s understand how much
we can do with Asp.Net Core built-in Logging

Asp.Net Core Built-in Logging


Before we learn about Logging implementation in Asp.Net Core, let’s
understand important logging classes, interface and functions in
Asp.Net Core Framework.

Namespace Microsoft.Extensions.Logging  . We learn about

ILoggingFactory, ILoggingProvider, ILogger, LoggingFactory Logging is

done using ILogger extension methods:

 LogDebug()
 LogInformation()
 LogWarning()
 LogError()
 LogCritical()

asp.net core logging appsettings.json


Setting up code in asppsetting.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

Now setup ILoggerFactory in Configure method of Startup.cs


public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{

loggerFactory.AddConsole(Configuration.GetSection("Logging"
));
loggerFactory.AddDebug();
//removed all other code for clarity
}

asp.net core logging dependency injection


We need to use ILogger, ILoggerFactory using dependency injection
in constructor

Now open your controller class and use dependency injection through

constructor, you can do that in two ways

public class homeController : Controller


{
ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
//you can have either one
public HomeController(ILoggerFactory loggerFactory)
{
_logger =
loggerFactory.CreateLogger(typeof(HomeController));
}
public IActionResult index()
{
_logger.LogInformation("just testing
LogInformation()");
_logger.LogError("There is no error, just testing
LogError()");
return View();
}
}

Log4net for Asp.net core logging


How to use third party logging utility like Log4Net with Asp.net Core.

Tough Asp.Net Core has built-in Logging mechanism, but I still


prefer Log4Net net because of many option of logging and easy to
implement.

Here are the few simple steps to implement Log4Net in your Asp.net
Core application.

Step 1
Install Log4Net utility using NugetPackage
Right Click on your project => Manage NuGet Package =>

log4net asp.net core configuration


Step 2
Create a xml file in root of the application with name
"log4net.config"
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="RollingFile" />
</root>
<appender name="RollingFile"
type="log4net.Appender.FileAppender">
<file value="D:\example.log" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d{hh:mm:ss} %message
%newline" />
</layout>
</appender>
</log4net>
</configuration>

Make sure you change the file tag value, mention your file path,
where you want file to be created.

Step 3
Now setup log4net Repository in Program.cs file
public class Program
{
public static void Main(string[] args)
{
var log4netRepository =
log4net.LogManager.GetRepository(Assembly.GetEntryAssembly(
));

log4net.Config.XmlConfigurator.Configure(log4netRepository,
new FileInfo("log4net.config"));
BuildWebHost(args).Run();
}
}

Step 4
Now open your controller class and setup _log4net local object, so
you can access all log4net methods in this controller, for example
we have called _log4net.Info() method in index.
public class HomeController : Controller
{
static readonly log4net.ILog _log4net =
log4net.LogManager.GetLogger(typeof(HomeController));
public IActionResult index()
{
_log4net.Info("Hello logging world log4net!");
return View();
}
}

Now run the application, and to check if log details written properly
in file you mentioned in <file value="D:\example.log" /> tag

Hope this was helpful!

ASP.NET Core MVC File Upload Example


In this tutorial you will learn  how to upload file in asp.net core ,
You will also learn how to retrieve those files and delete from folder
under wwwroot.
File Uploading Example in Asp.Net Core
First we design a form in razor view that will allow us to browse and
upload one or multiple images from local machine.

Form design in Razor View, Note: If you specify multiple in input file
field, which means it will allow multiple files to be selected and
uploaded.
<form method="post" enctype="multipart/form-data" asp-
controller="FileUpload" asp-action="index">
<div class="form-group">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div>
</div>
</form>

Add Middleware Service in Startup


You need to add following Middleware Service reference in
ConfigureServices method of Startup.cs file. In your
ConfigureService method there may be many other services already
added, so just add IFileProvider Service also.
using Microsoft.Extensions.FileProviders;
using System.IO;

public void ConfigureServices(IServiceCollection services)


{
services.AddSingleton<IFileProvider>(new
PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot")));
services.AddMvc();
}

Get file path in asp.net Core


To get folder reference in Asp.net Core Controller you need to Add
IHostingEnvironment in Controller with DI

Now you need the folder reference where you want to save all
uploaded image files, and to get that you need an instance of
IHostingEnvironment, so in controller constructor we create the
instance using dependency injection
private readonly IHostingEnvironment _hostingEnvironment;

public fileuploadController(IHostingEnvironment
hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}

File Upload Controller Code


Finally we write the controller code where we process the files
posted from image upload form in razor view.

Note: while creating FileStream object pass file name with folder
Path, if you pass only folder Path in FileStream, You may get
UnauthorizedAccessException while uploading file in asp.net core
application.
using Microsoft.Extensions.FileProviders;
using System.IO;

[HttpPost("FileUpload")]
public async Task<IActionResult> index(List<IFormFile>
files)
{
if (files == null || files.Count == 0)
return Content("file not selected");
long size = files.Sum(f => f.Length);
var filePaths = new List<string>();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
// full path to file in temp location
var filePath =
Path.Combine(_hostingEnvironment.WebRootPath,
"userimages");

filePaths.Add(filePath);

var fileNameWithPath =
string.Concat(filePath,"\\",formFile.FileName);

using (var stream = new


FileStream(fileNameWithPath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without
validation.
return Ok(new { count = files.Count, size,
filePaths });
}

Hope you have understood the implementation of file uploading in


asp.net core

Now probably you would like to know  how to retrieve and display
any uploaded file from any folder under wwwroot in asp.net core !
Retrieve static files in Asp.net Core

Retrieve images from wwwroot


In earlier article i shared how to  upload multiple image files in
asp.net core wwwroot folder

Now we learn how to retrieve image files from any folder under
wwwroot, display images on screen and delete image in asp.net core
web application.

Load Images in Controller Asp.net Core


First we design a model with few properties, so in controller we can
fill those properties and access in razor view, in model we have a
FileInfo array type property called “Files”, we will use this property
for retrieving images from a folder under wwwroot in Asp.net core
Here is how the model code will look like.
namespace WebTrainingRoom.Models
{
public class FileManagerModel
{
public FileInfo[] Files { get; set; }
public IFormFile IFormFile { get; set; }
public List<IFormFile> IFormFiles { get; set; }
}
}

We need to access the root folder of the application in our controller


code, and to do that we need use PhysicalFileProvider service.

Add Middleware Service in Startup


You need to add following Middleware Service reference in
ConfigureServices method of Startup.cs file. In your
ConfigureService method there may be many other services already
added, so just add IFileProvider Service also.
using Microsoft.Extensions.FileProviders;
using System.IO;
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFileProvider>(new
PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot")));
services.AddMvc();
}

Get file path in asp.net Core


To get folder reference in Asp.net Core Controller you need to Add
IHostingEnvironment in Controller with DI (Dependency Injection)
Now you need the folder reference where you want to save all
uploaded image files, and to get that you need an instance of
IHostingEnvironment, so in controller constructor we create the
instance using dependency injection
private readonly IHostingEnvironment _hostingEnvironment;
public fileuploadController(IHostingEnvironment
hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}

Now whenever you want to access wwwroot folder in your controller,


just write _hostingEnvironment.WebRootPath
Now in controller code we fetch all images from specified folder
(“userimages” under “wwwroot”) , and set in model property (File
Array)
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using WebTrainingRoom.Models;

public IActionResult index()


{
FileManagerModel model = new FileManagerModel();
var userImagesPath =
Path.Combine(_hostingEnvironment.WebRootPath,
"userimages");
DirectoryInfo dir = new DirectoryInfo(userImagesPath);
FileInfo[] files = dir.GetFiles();
model.Files = files;
return View(model);
}

Display images from wwwroot folder


Finally, we need to display all images in our asp.net core razor view;
we also have a provision to delete any image from this screen also
from file system (folder under "wwwroot")
@if (Model.Files != null)
{
foreach (FileInfo f in Model.Files)
{
<div class="col-lg-3">
<img src="~/userimages/@f.Name"
style="width:90%;">
<div style="padding:10px;text-align:center"><a
href="@Url.Action("deletefile","fileupload",new
{ fname=f.Name})">Delete</a></div>
</div>
}
}
<div class="clearfix"></div>

Please take a look at the screen below.


Delete Image from folder in Asp.net core
Now as you see there is delete link under each screen in above
image, once you click the image will be deleted from folder
permanently and the screen will be reloaded without that image.
In razor view you need to just pass the unique identifier for that
image to call an action, here I am passing the image name.
<a href="@Url.Action("deletefile","fileupload",new
{ fname=f.Name})">Delete</a>
Now in controller we have to write action method to receive the
delete request and finally delete that image from folder and
redirecting to a different action method.
public IActionResult deletefile(string fname)
{
string _imageToBeDeleted =
Path.Combine(_hostingEnvironment.WebRootPath,
"userimages\\",fname);
if ((System.IO.File.Exists(_imageToBeDeleted)))
{
System.IO.File.Delete(_imageToBeDeleted);
}
return RedirectToAction("index",new { deleted=
fname });
}
Hope you understood retrieving, displaying and deleting files from
asp.net core folder

Microservices in .Net Core

What is Microservices in .Net Core?


Microsoft has introduced a service oriented architecture that can be
containerized and independent. Microservices are type of API
service, that are small, modular, can be deployed independently,
which can run in an isolated environment.

You also can say Microservices is a type of SOA (Service Oriented


Architecture), an architectural design that separates portions of an
application into small, self-containing services, one Microservice can
have multiple services within it, but it’s designed as small as
necessary.

There is fantastic document for  .NET Microservices Architecture


Guidance from Microsoft.

Microservices Characteristic
 Any microservice is self independent, deployment and
consumption will not depend on anything, so if you have
multiple micro services as a part of any big enterprise
system, there are chances that you may have same data
duplicated in different micro service, as per micro service
design principal that’s not incorrect design.
 So while designing any microservices we should try to
minimize the interaction between the internal microservices,
the less interaction between microservices is better, but in
some situation you may need to integrate other
microservices as per business demand, in such cases make
sure all communication are asynchronous.

Microservices Architecture
As explained earlier micro services are small independent service
that can interact with any number of services or different type of
clients, but to understand it in typical enterprise scenario where
probably we can have any number of micro services and any number
of applications, following picture is the representation of one such
scenario .
Difference between Web API and Microservices
At this point you may think what’s the difference between Web API
and Microservices, because there are many similarities.
The main conceptual difference is, Microservices is an architectural
pattern of building small independent services that can work with
multiple systems, so from business point of view, you can build
multiple Microservices rather than building a big system together.
When API is designed for providing a cross platform data
interoperability mechanism, where Microservices is much bigger
picture.
Now if you think of a big enterprise business, where business
demand is constantly changing, and there are so many
interdependency factors, so maintaining everything in one system
become tough, impact analysis takes lots of time, also there are high
risk involved. And that’s where Microservices makes the job much
easier and easy to maintain, that’s the reason Microservices
architecture is becoming so popular
How to build Microservices
Here I will explain you a simple step of building small microservice
from scratch

Select .Net Core framework and “API ” project, if your operating system
supports docker then you can enable docker otherwise ignore , (if you
are developing on windows 10 then probably you have docker support, if
using windows 7, then please ignore )
Globalization and Localization with Asp.Net Core
Learn how to implement  Globalization and Localization in
Asp.Net Core application

Implement Globalization and Localization


What is Globalization?

Globalization is the process of making a globalised web application,


which means there will be different content for different geography,
means localised content.

What is Localization?
Localization is the process of setting up content for local geography,
continuation process of globalization.

Asp.net core provides mechanism of adding local culture info into


middleware
using Microsoft.AspNetCore.Localization;
using System.Globalization;

IList<CultureInfo> supportedCultures = new


List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("fi-FI"),
};

app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});

Localization Setup
To setup localization in controller you need to add following code.

Things to notice

 Required namespace
 Dependency Injection through constructor
 Using the instance of IStringLocalizer
Note:

Like earlier version of Asp.net we still can use resource file (.resx) to

store localization information in the form of key-value pair, but now in

asp.net core we can store localization information in Json file  (.json)

too, the disadvantage of keeping information in resx file is, that every

time we add a new key, we need to compile the assembly for that key to

get reflected, on the other hand using JSON file we can add any key and

use them in razor view without compiling the whole assembly again.

Controller Setup

Here is how localization can be implemented in controller level, also


have a provision to change the current culture by user from UI
through query string
using Microsoft.Extensions.Localization;
using Microsoft.AspNetCore.Mvc;
using System.Globalization;

public class welcomeController : Controller


{
private readonly IStringLocalizer<welcomeController>
_localizer;

public
welcomeController(IStringLocalizer<welcomeController>
localizer)
{
_localizer = localizer;
}

public IActionResult index()


{
return View();
}

public IActionResult hello()


{
string currentCulture = Request.Query["culture"];
if (!string.IsNullOrEmpty(currentCulture))
{
CultureInfo.CurrentCulture = new
CultureInfo(currentCulture);
}
ViewData["WelcomeMessage"] =
_localizer["WelcomeMessage"];
return View();
}
}

Implement Localization Step by Step


Here is the complete localization implementation with working code
(you can straight away use the code in your project)

Step 1

Right click on your project then "Manage NuGet Packages", and then
add following two packages in your solution

Microsoft.AspNetCore.Localization
Microsoft.AspNetCore.Localization.Routing

Install NuGet package "Askmethat.Aspnet.JsonLocalizer"

Step 2
Open your Startup.cs file and add following code in
"ConfigureServices" method.
public void ConfigureServices(IServiceCollection services)
{
#region Localization
services.AddSingleton<IdentityLocalizationService>();
services.AddLocalization(o =>
{
// We will put our translations in a folder called
Resources
o.ResourcesPath = "Resources";
});
services.AddSingleton<IStringLocalizerFactory,
JsonStringLocalizerFactory>();
services.AddSingleton<IStringLocalizer,
JsonStringLocalizer>();
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFo
rmat.Suffix,
opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization(options =>
{
});

CultureInfo.CurrentCulture = new CultureInfo("en-US");


#endregion
}

Notice how default culture has been set


using CultureInfo.CurrentCulture

Now add the following code in "Configure" method of same


startup.cs file
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
#region Localization
IList<CultureInfo> supportedCultures = new
List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("en-IN"),
new CultureInfo("fr-FR"),
};
var localizationOptions = new
RequestLocalizationOptions
{
DefaultRequestCulture = new
RequestCulture(culture: "en-US", uiCulture: "en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
app.UseRequestLocalization(localizationOptions);

var requestProvider = new


RouteDataRequestCultureProvider();
localizationOptions.RequestCultureProviders.Insert(0,
requestProvider);
var locOptions =
app.ApplicationServices.GetService<IOptions<RequestLocaliza
tionOptions>>();
app.UseRequestLocalization(locOptions.Value);

#endregion
}

Step 3
You need to write following custom classes for localization in Json
format. Let's create a class with name "JsonLocalization"
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
namespace WebTrainingRoom
{
class JsonLocalization
{
public string Key { get; set; }
public Dictionary<string, string> LocalizedValue =
new Dictionary<string, string>();
}
public class JsonStringLocalizerFactory :
IStringLocalizerFactory
{
public IStringLocalizer Create(Type resourceSource)
{
return new JsonStringLocalizer();
}
public IStringLocalizer Create(string baseName,
string location)
{
return new JsonStringLocalizer();
}
}
public class JsonStringLocalizer : IStringLocalizer
{
List<JsonLocalization> localization = new
List<JsonLocalization>();
public JsonStringLocalizer()
{
//read all json file
JsonSerializer serializer = new
JsonSerializer();
localization =
JsonConvert.DeserializeObject<List<JsonLocalization>>(File.
ReadAllText(@"Resources/localization.json"));
}
public LocalizedString this[string name]
{
get
{
var value = GetString(name);
return new LocalizedString(name, value ??
name, resourceNotFound: value == null);
}
}
public LocalizedString this[string name, params
object[] arguments]
{
get
{
var format = GetString(name);
var value = string.Format(format ?? name,
arguments);
return new LocalizedString(name, value,
resourceNotFound: format == null);
}
}
public IEnumerable<LocalizedString>
GetAllStrings(bool includeParentCultures)
{
return localization.Where(l =>
l.LocalizedValue.Keys.Any(lv => lv ==
CultureInfo.CurrentCulture.Name)).Select(l => new
LocalizedString(l.Key,
l.LocalizedValue[CultureInfo.CurrentCulture.Name], true));
}
public IStringLocalizer WithCulture(CultureInfo
culture)
{
return new JsonStringLocalizer();
}
private string GetString(string name)
{
var query = localization.Where(l =>
l.LocalizedValue.Keys.Any(lv => lv ==
CultureInfo.CurrentCulture.Name));
var value = query.FirstOrDefault(l => l.Key ==
name);
return
value.LocalizedValue[CultureInfo.CurrentCulture.Name];
}
}
}

Notice in above code, we have specified the json file location


at File.ReadAllText(@"Resources/localization.json") . Means in
root of the application there is a folder called “Resources” , then
there is a file called "localization.json"

Step 4
Now create a class with name “IdentityLocalizationService”. Now
create a class with name “IdentityLocalizationService”, in this class
we have methods that will allow us to access localized string based
on key
using Microsoft.Extensions.Localization;
using System.Reflection;

namespace WebTrainingRoom.Resources
{
public class IdentityLocalizationService
{
private readonly IStringLocalizer _localizer;
public
IdentityLocalizationService(IStringLocalizerFactory
factory)
{
var type = typeof(IdentityResource);
var assemblyName = new
AssemblyName(type.GetTypeInfo().Assembly.FullName);
_localizer = factory.Create("IdentityResource",
assemblyName.Name);
}
public LocalizedString
GetLocalizedHtmlString(string key)
{
return _localizer[key];
}
public LocalizedString
GetLocalizedHtmlString(string key, string parameter)
{
return _localizer[key, parameter];
}
}

public class IdentityResource


{
}

Step 5

If you want multiple-localization to be implemented, then you need


to add multiple json file with same key values.
en-US.json
{
"WelcomeMessage": "Welcome to my World."
}

en-IN.json
{
"WelcomeMessage": "Namaskar! Apne Ghar Ayyea"
}

You also can write all in one json file


[
{
"Key": "WelcomeMessage",
"LocalizedValue" : {
"fr-FR": "Bienvenue dans mon monde.",
"en-US": "Welcome to my Home.",
"en-IN": "Swagatam! Apne Ghar Ayyea."
}
}
]
How to change current culture
You may need to provide an option of changing current culture to
your web page visitor, so in case they want to change the current
culture, they can easily switch to their native culture
CultureInfo.CurrentCulture = new CultureInfo("en-IN");

string currentCulture = Request.Query["culture"];


if (!string.IsNullOrEmpty(currentCulture))
CultureInfo.CurrentCulture = new
CultureInfo(currentCulture);

How to get the list of all CultureInfo


Here are few lines of code can get you the list of all culture info, so
you can set the right culture for your required geography, remember
you need to use the right culture name; otherwise it may get you
error.
using System;
using System.Globalization;
using System.Collections.Generic;

List<string> list = new List<string>();


foreach (CultureInfo ci in
CultureInfo.GetCultures(CultureTypes.AllCultures))
{
list.Add(String.Format("{0} / {1}", ci.Name,
ci.EnglishName));
}
list.Sort(); // sort by name

You might also like