Consuming Web Service Using HttpWebRequest

Previously I have written many articles on web services right from creating to consuming web services and it has huge response , Now in this article we will learn how to consume or call web service using  HttpWebRequest class.

This approach sometimes we need when consuming the third party web services where we don't know much about the endpoints and configuration of web services . In this article we will not be create any web service because we have already created it So If wants to learn basics of the web services please refer my previous articles.
 I hope you read above articles , Now lets learn how to Call Web Service using SOAP request in console application step by step so beginners also can understand .

Step 1: Find the Web Service SOAP Request Body.

In this article We are not going to create web service because we have already created it and if you wants to create web service and learn about it then please refer my preceding articles.

So lets find out the SOAP request body which is used to pass input parametes and invoke the web service . I have one web service which is hosted in in my local IIS .So paste your web service url into the browser and wait till following response come which is shown in following image.
In the above screen shot , you might be noticed that there are three web methods in the web service named Addition , EmployeeDetails and HelloWorld. Now click on one of the method which you wants to invoke , After clicking on web method it shows SOAP request and SOAP Response body , find out the SOAP request body which is shown in the following image.
In the above image , We are clearly observing that , It shows the all details how to make SOAP request and also showing parameter values which is require to invoke service using HttpWebRequest . So lets learn in brief about those parameters .

  •  HTTP Method: It's nothing but the what type of HTTP request you wants to make to the service such as GET , POST ,PUT or delete.

  •  Host: It defines the url where is the service hosted , in our scenario our host is localhost , i.e http://localhost/Employee.asmx.

  • Content-Type: It defines what type of content type request you are making such as XML or json now in our scenario its text/xml.

  •  Content-Length: It defines the content length of request body.

  •  SOAPAction: This is very important attribute to identify specific web method and call it from multiple web methods .

  • SOAP Body: It contains the request and response body.
I hope you learned about SOAP request parameter , Now copy the soap envelope part to use it as SOAP request which we will use in our console application.

Step 2: Create the Console application to call Web Service
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2015".

  2. "File" - "New" - "Project..." then in the New Project window, console "C#" - ".

  3. Give the project a name, such as "UsingSOAPRequest" or another as you wish and specify the location.
Now open Program.cs file and write the following method to create HttpWebRequest as:
public HttpWebRequest CreateSOAPWebRequest()    
    {    
        //Making Web Request    
        HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://localhost/Employee.asmx");    
        //SOAPAction    
        Req.Headers.Add(@"SOAPAction:http://tempuri.org/Addition");    
        //Content_type    
        Req.ContentType = "text/xml;charset=\"utf-8\"";    
        Req.Accept = "text/xml";    
        //HTTP method    
        Req.Method = "POST";    
        //return HttpWebRequest    
        return Req;    
    }    
Now Let's create the method to invoke the web service using SOAP request bo
public void InvokeService(int a, int b) {  
      //Calling CreateSOAPWebRequest method    
      HttpWebRequest request = CreateSOAPWebRequest();  
      
      XmlDocument SOAPReqBody = new XmlDocument();  
      //SOAP Body Request    
      SOAPReqBody.LoadXml(@ "<?xml version="  
       "1.0"  
       " encoding="  
       "utf-8"  
       "?>   < soap: Envelope xmlns: soap = ""  
       http: //schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">    
       < soap: Body >  
       < Addition xmlns = ""  
       http: //tempuri.org/"">    
       < a > " + a + @" < /a>   < b > " + b + @" < /b>   < /Addition>   < /soap:Body>   < /soap:Envelope>");    
      
      
       using(Stream stream = request.GetRequestStream()) {  
        SOAPReqBody.Save(stream);  
       }  
       //Geting response from request    
       using(WebResponse Serviceres = request.GetResponse()) {  
           using(StreamReader rd = new StreamReader(Serviceres.GetResponseStream())) {  
               //reading stream    
               var ServiceResult = rd.ReadToEnd();  
               //writting stream result on console    
               Console.WriteLine(ServiceResult);  
               Console.ReadLine();  
           }  
       }  
    }  
Now call above method from main method by writing following code as:
static void Main(string[] args)    
    {    
        //creating object of program class to access methods    
        Program obj = new Program();    
        Console.WriteLine("Please Enter Input values..");    
        //Reading input values from console    
        int a = Convert.ToInt32(Console.ReadLine());    
        int b = Convert.ToInt32(Console.ReadLine());    
        //Calling InvokeService method    
        obj.InvokeService(a, b);    
    }    
Now whole code in Program.cs file will be look like as follows:
using System;  
using System.IO;  
using System.Net;  
using System.Xml;  
  
namespace UsingSOAPRequest  
{  
    public class Program  
    {  
        static void Main(string[] args)  
        {  
            //creating object of program class to access methods  
            Program obj = new Program();  
            Console.WriteLine("Please Enter Input values..");  
            //Reading input values from console  
            int a = Convert.ToInt32(Console.ReadLine());  
            int b = Convert.ToInt32(Console.ReadLine());  
            //Calling InvokeService method  
            obj.InvokeService(a, b);  
        }  
        public void InvokeService(int a, int b)  
        {  
            //Calling CreateSOAPWebRequest method  
            HttpWebRequest request = CreateSOAPWebRequest();  
  
            XmlDocument SOAPReqBody = new XmlDocument();  
            //SOAP Body Request  
            SOAPReqBody.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>  
            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-   instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">  
             <soap:Body>  
                <Addition xmlns=""http://tempuri.org/"">  
                  <a>" + a + @"</a>  
                  <b>" + b + @"</b>  
                </Addition>  
              </soap:Body>  
            </soap:Envelope>");  
  
  
            using (Stream stream = request.GetRequestStream())  
            {  
                SOAPReqBody.Save(stream);  
            }  
            //Geting response from request  
            using (WebResponse Serviceres = request.GetResponse())  
            {  
                using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))  
                {  
                    //reading stream  
                    var ServiceResult = rd.ReadToEnd();  
                    //writting stream result on console  
                    Console.WriteLine(ServiceResult);  
                    Console.ReadLine();  
                }  
            }  
        }  
  
        public HttpWebRequest CreateSOAPWebRequest()  
        {  
            //Making Web Request  
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://localhost/Employee.asmx");  
            //SOAPAction  
            Req.Headers.Add(@"SOAPAction:http://tempuri.org/Addition");  
            //Content_type  
            Req.ContentType = "text/xml;charset=\"utf-8\"";  
            Req.Accept = "text/xml";  
            //HTTP method  
            Req.Method = "POST";  
            //return HttpWebRequest  
            return Req;  
        }  
    }  
}  
Now run the console application ,then the console windows will be look like as follows and enter the input values as:
 Now press enter button , it will give the response in XML format are as follows:

In preceding console window you have seen web service response in the form of XML format which contains the output as 300 . I hope from all above example you have learned how to call web service using SOAP request in console application.

Notes
  • Apply proper validation as per your need.
Summary

I hope this article is useful for all readers , if you have any suggestions related to this article then please contact me.

Don't Forget To  
Related articles

Creating Strongly Typed CheckBox List in ASP.NET MVC

This article will demonstrate the how to create strongly typed checkbox list in ASP.NET MVC application, So lets learn step by step about it.

Step 1 : Create an MVC Application.
Now let us start with a step by step approach from the creation of simple MVC application as in the following:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project..." then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK . 
 Step 2 : Add Model class
Right click on model folder of created MVC application project and add  class named CheckBoxModel.cs
CheckBoxModel.cs
public class CheckBoxModel
    {
        public int Value { get; set; }
        public string Text { get; set; }
        public bool IsChecked { get; set; }
    }
    public class CheckBoxList
    {
        public List<CheckBoxModel> CheckBoxItems { get; set; }
    }
 Step 2 : Add Controller
Right click on Controllers folder of created MVC application and add Controller named HomeController.cs
 HomeController.cs
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            //Creating object of CheckBoxList model class
            CheckBoxList ChkItems = new CheckBoxList();
            //Additng items to the list
            List<CheckBoxModel> ChkItem = new List<CheckBoxModel>()
            {
              new CheckBoxModel {Value=1,Text="ASP.NET",IsChecked=true },
              new CheckBoxModel {Value=1,Text="C#",IsChecked=false },
              new CheckBoxModel {Value=1,Text="MVC",IsChecked=false },
              new CheckBoxModel {Value=1,Text="Web API" ,IsChecked=false},
              new CheckBoxModel {Value=1,Text="SignalR",IsChecked=false },
              new CheckBoxModel {Value=1,Text="SQL" ,IsChecked=false},
            };
            //assigning records to the CheckBoxItems list 
            ChkItems.CheckBoxItems = ChkItem;
            return View(ChkItems);
           
        }

    }
 Step 3: Add View
Right click on View folder of created MVC application project and add empty view named Index.cshtml. Now open the Index.cshtml view and write the following code into the view
@model BindCheckBoxListInMVC.Models.CheckBoxList
@{
    ViewBag.Title = "www.compilemode.com";
}
<div class="form-horizontal">
    <h4>Select your favourite Subjects</h4>
        @foreach (var item in Model.CheckBoxItems)
        {
            <input id="chk@(item.Value)"
                   type="checkbox"
                   value="@item.Value" 
                   checked="@item.IsChecked" />
                @item.Text <br />
        }
       
</div>
Now everything is ready ,run the application then the check box list will be look like as follows .
From all above example we have learned how to create strongly typed checkbox list in ASP.NET MVC.
Summary
I hope this article is useful for all readers, if you have a suggestion then please contact me.
Don't Forget To  

Related articles

Routing in ASP.NET MVC

In today's modern web application each and every thing is important including request URL pattern of the application to make application more traffic driven and user friendly. In earlier ASP.NET application all the user request are mapped with physical file location that is with .aspx pages. These types of URL pattern are won't be customized to make it user, SEO friendly and most of the time in ASP.NET application to overcome these URL drawback URL rewriting technique is used, But still it unable to fulfill the expected requirement.
In ASP.NET MVC, URL pattern is completely different as compare to the ASP.NET application URL pattern, So lets learn about the ASP.NET MVC routing.

What is routing in ASP.NET MVC ?
Routing is the concept in ASP.NET MVC which is used to define the URL pattern for the ASP.NET MVC application incoming user request.
There are two types of routing supported by ASP.NET MVC
  • Conventional based routing 
  • Attribute routing
Conventional Routing
The default routing in ASP.NET MVC is a conventional routing which is get added in RouteConfig.cs file when we create ASP.NET MVC application, These type of routing defined in RouteConfig.cs file .

The following is the default routing

Suppose we have Employee method in ASP.NET MVC application and we want to define the URL pattern that how this method can be called by end user then routing pattern can be defined as in the following

Attribute Routing
The routing which is defined on controller or action level is called as attribute routing . These type of routing is only supports in  MVC 5 version onward
I hope from preceding brief explanation you have learned about the ASP.NET MVC routing, In my next article we will learn each of the routing in details with real time examples.
    The preceding is the example of attribute routing which can be enabled in RouteConfig.cs by calling MapMvcAttributeRoutes method of RouteCollection class
    
    Key Points
    • RouteCollection class is used for routing which uses the System.Web.Routing namespace
    • ASP.NET MVC 5 supports two types of routing that is conventional and attribute routing
    • Conventional based is the default routing in ASP.NET MVC 
    • Attribute routing can be defined on controller as well as action level
    • All routes should be registered into the Global.asax file .
    • Every ASP.NET MVC application must have at least one routing defined
    • We can define multiple routing in single application in this case it executed sequence wise as it defined.
    • If we are defining two route templates then the route name must be different across the application level
    Summary
    I hope, this article is useful for all the readers. If you have any suggestions, please contact me. In my next article we will learn real time example of conventional and attribute routing.

    Don't Forget To  

    Top 10 Features of Visual Studio 2017

    Microsoft launches the Visual Studio 2017 with lots of features some them are even not predicated such as Visual studio can support other languages other than Microsoft origin and also Visual studio can be get installed on other operating system than the Microsoft windows operating system, Now all is possible you can installed visual studio on Linux & Mac OS as well also you can develop the application using multiple open source languages which are not developed by Microsoft .
    Microsoft changing lot day by day by making visual studio universal application development platform using any programming language. Visual studio 2017 comes with the following editions which can be installed on Windows and Mac operating system
    • Visual Studio Community
    • Visual Studio Professional
    • Visual Studio Enterprise
    • Visual Studio Code
    Visual Studio Community

    This is a free edition having fully featured which can be used for students, open-source project contribution, individual developers and non-enterprise organization having not more than five users.
    Visual Studio Professional
    This is a commercial editions having Professional developer tools, services, and subscription benefits for small teams which can be used by purchasing the licensed copy.
    Visual Studio Enterprise
    This is a commercial editions having the features to meet end-to-end solution where high demand of quality and scale the team in all sizes. enterprise edition can be used by purchasing license.
    Visual Studio Code
    This is a Free, open source edition of visual studio which cab be used to develop the application using wide range of open source programming languages. Visual studio code can be installed on Mac, Windows and Linux operating system.
    Let's learn about top 10 features of visual studio 2017 which can be differ from edition to edition
    Install what you wants
    Now you can install the specific components whatever you wants which makes visual studio installation much  faster than previous edition
    Contentious Integration and Deployment (DevOps)
    Now you can configure CI-CD pipeline directly from the visual studio IDE itself
    Integration with Cloud
    You can integrate all visual studio developed application to Microsoft azure such as you can deploy your application on Microsoft azure directly from the visual studio and lot more
    Lightweight Solution Load
    Now you can load the projects in visual studio solution explorer very faster using lightweight solution load feature which is useful when your project solution contains multiple projects.
    Live Unit Testing
    Now you can test your code once you save your changes in visual studio editor instead of running test methods separately, This feature can help to fix the code issue while doing the real time development instead of fixing it later & change your code again.
    Enforcing code styles and conventions
    Now you can define your coding style and conventions directly from the visual studio and force developer to follow your defined coding standards which will help to achieve uniformity in coding standards across your project team developers.
    Architectural Dependency Validation
    Now you can validate your project architectural dependencies which will helpful to remove the unwanted  dependencies from your project & improve the performance as well as security.
    Improvements to code navigation
    Now can navigate easily into the code from visual studio to search classes and methods of  your project also visual studio 2017 makes very easier to find all references of particular variable or methods of your project.
    IntelliSense filtering
    Now you can filter the intellisense and find the appropriate properties and methods very easily.
    The revised Start page
    Click to Run Debugging
    Now you can debug your specific line of code without setting the debug point with the help of click to run feature.
    Summary
    I hope this article is useful for all readers, In my next article we will learn in details of each feature, If you have any suggestions please contact me.
     
    Don't Forget To 

    Mapping Stored Procedure Parameter with Dapper ORM Using DynamicParameters

    In this article we will learn how to map stored procedure parameter with Dapper ORM using DynamicParameters class of Dapper, Let's demonstrate it with step by step examples,
    Suppose you have following model class which values assigned from UI

    public class EmpModel
        {
            [Display(Name = "Id")]
            public int Empid { get; set; }
            [Required(ErrorMessage = "First name is required.")]
            public string Name { get; set; }
            [Required(ErrorMessage = "City is required.")]
            public string City { get; set; }
    
            [Required(ErrorMessage = "Address is required.")]
            public string Address { get; set; }
        }


    Now consider following stored procedure we have

    Create procedure [dbo].[AddNewEmpDetails]  
    (  
       @Name varchar (50),  
       @City varchar (50),  
       @Address varchar (50)  
    )  
    as  
    begin  
       Insert into Employee values(@Name,@City,@Address)  
    End  


    Now following is the function which is used to map the stored procedure with Dapper

       public bool AddEmployee(EmpModel obj)
            {     
                    DynamicParameters param = new DynamicParameters();
                    param.Add("@Name", obj.Name);
    param.Add("@City", obj.City);
    param.Add("@Address",obj.Address);
                    connection();
                    con.Open();
                    con.Execute("AddNewEmpDetails", param, commandType: CommandType.StoredProcedure);
                    con.Close();
                    return true;         
            }
     
    
    
    
    
    In the above function
    •  Connection() is the method which contains the connection string .
    •  Con is the SqlConnection class object.
    • AddNewEmpDetails is the stored procedure.
    •  DynamicParameters is the Dapper class name to map parameter like as SqlCommand
    • EmpModel is  model class.
    Summary
    I hope this article is useful for all readers. If you have any suggestions please contact me.Don't Forget To  


    Upload Images on Server Folder Using ASP.NET MVC

    Sometimes we require to upload the images on the server folder for specific requirement so by considering this requirement I have decided to write this article, Let's demonstrate step by step  
    Step 1: Create an MVC Application.
    Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. Click "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
     Step 2: Create Model Class
    Now let us create the model class named FileUploadModel.cs by right clicking on Models folder as in the following screenshot:

    Write the following code into the FileUploadModel.cs as follows

    FileUploadModel.cs 
    public class FileUploadModel   
          {    
              [DataType(DataType.Upload)]    
              [Display(Name = "Upload File")]    
              [Required(ErrorMessage = "Please choose file to upload.")]    
              public string file { get; set; }    
            
          }   
    
    Step 3 : Add Controller Class.

    Now let us add the MVC 5 controller as in the following screenshot:

     After clicking on Add button it will show the window. Specify the Controller name as FileUpload with suffix Controller.
    Note:
    The controller name must be having suffix as 'Controller' after specifying the name of controller. Now lets modify the default code in FileUploadController.cs to read uploaded files .
    There are many ways to read the uploaded files in controller but in this article we will learn two ways to read the uploaded files into the controller which are listed below,
    • HttpRequestBase: We can use HttpRequestBase class property named Request to get collection of files or single file.
    • HttpPostedFileBase: This is the easiest way to read the uploaded files into the controller .
    Now let's open the FileUploadController.cs class file and write the following code to read file using HttpRequestBase class.

    FileUploadController.cs
     
    [HttpPost]    
               public ActionResult UploadFiles(HttpPostedFileBase file)    
               {    
                   if (ModelState.IsValid)    
                   {    
                       try    
                       {    
                             
                           //Method 2 Get file details from HttpPostedFileBase class    
            
                           if (file != null)    
                           {    
                               string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
                               file.SaveAs(path);     
                           }    
                           ViewBag.FileStatus = "File uploaded successfully.";    
                       }    
                       catch (Exception)    
                       {      
                           ViewBag.FileStatus = "Error while file uploading."; ;    
                       }                  
                   }    
                   return View("Index");    
               }  
    

    Following is the whole source code of FileUploadController.cs file which will look like as follows,

        using System;    
        using System.IO;    
        using System.Web;    
        using System.Web.Mvc;    
            
        namespace UploadingFilesUsingMVC.Controllers    
        {    
            public class FileUploadController : Controller    
            {    
                // GET: FileUpload    
                public ActionResult Index()    
                {    
                    return View();    
                }    
                [HttpPost]    
                public ActionResult UploadFiles(HttpPostedFileBase file)    
                {    
                    if (ModelState.IsValid)    
                    {    
                        try    
                        {    
                              
            
                            if (file != null)    
                            {    
                                string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));    
                                file.SaveAs(path);    
            
                            }    
                            ViewBag.FileStatus = "File uploaded successfully.";    
                        }    
                        catch (Exception)    
                        {    
            
                            ViewBag.FileStatus = "Error while file uploading.";    
                        }    
                         
                    }    
                    return View("Index");    
                }    
            }    
        }   
    
    Step 4 : Creating view named Index using FileUploadModel class .

    Right click on View folder of created application and choose add view, select FileUploadModel class and choose create scaffolding template,
    Click on Add button, then it will create the view named index. Now open the Index.cshtml view, then the following default code you will see which is generated by MVC scaffolding template as,
    Index.cshtml

    @model UploadingFilesUsingMVC.Models.FileUploadModel
    
    @{
        ViewBag.Title = "www.compilemode.com";
    }
    
    @using (Html.BeginForm("UploadFiles", "FileUpload", FormMethod.Post,new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.file, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "form-control", @type="file"} })
                    @Html.ValidationMessageFor(model => model.file, "", new { @class = "text-danger" })
                </div>
            </div>
            
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Upload" class="btn btn-primary" />
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10 text-success">
                    @ViewBag.FileStatus
                </div>
            </div>
        </div>
    }
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    

    Step 4 : Create a folder named UploadedFiles or as you wish to save uploaded files,
    Right click on created ASP.NET MVC application, solution explorer and choose add new item, then Add New Folder. After adding the model, view, controller and UploadedFiles folder to save the file. Solution explorer will look like as follows,


    Now we have done all coding to upload files.
    Step 5: Now run the application. After running the application initial screen will look as follows,

     Now click on Upload button without selecting file then the following error message is visible which we have defined in model class as,

     Now browse the file and click on upload button, It will show the following message after successfully uploading the file as,

    Now lets see the UploadedFiles folder where our uploaded files are saved, Browse the folder or move the mouse cursor or image then uploaded image will look like as follows,

    I hope from all the preceding examples we have learned how to upload files on server folder .
    Note:

    • HttpPostedFileBase instance name must be a file.
    • Model class property name must be file so it can generate the input type file .
    • Its important to define enctype = "multipart/form-data" in form action otherwise file value will be null in controller .
    • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
    Summary
    I hope this article is useful for all readers. If you have any suggestions please contact me.
    Don't Forget To 

    Bind Country List Using CultureInfo In ASP.NET MVC

    In this article we will learn how to populate list of countries using C# globalization class which is capable to display the countries list.

    Now let's start creating a simple MVC  application to demonstrate how to get list of countries without database in ASP.NET MVC using Globalization class

    Step 1: Create an MVC Application.

    Now let us start with a step by step approach from the creation of a simple MVC application as in the following,
    1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear,

    Step 2: Add Controller Class

    Now let us add the MVC 5 controller as in the following screenshot,

    After clicking on Add button it will show the window. Specify the Controller name as Home with suffix Controller.
    Now modify the default code in HomeController.cs class file and create the action methods, after modifying the code will look like as follows,
    HomeController.cs
     
    using System.Collections.Generic;
    using System.Globalization;
    using System.Web.Mvc;
    
    namespace DisplayCountryList.Controllers
    {
        public class HomeController : Controller
        {
            // GET: Home
            public ActionResult Index()
            {
                List<string> CountryList = new List<string>() ;
                CultureInfo[] CInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
                foreach (CultureInfo CInfo in CInfoList)
                {
                    RegionInfo R = new RegionInfo(CInfo.LCID);
                    if (!(CountryList.Contains(R.EnglishName)))
                    {
                        CountryList.Add(R.EnglishName);
                    }
                }
    
                CountryList.Sort();
                ViewBag.CountryList = CountryList;
                return View();
            }
        }
    }

    Step 3: Create View

    Right click on view folder or near Index Action method and Add view with name Index and modify the existing view code , After modifying the code the Index.cshtml will be look like as follows

    @{
        ViewBag.Title = "www.compilemode.com";
    }
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <hr />
            <div class="form-group">
                <label class="col-md-2 control-label">Select Country</label>
                <div class="col-md-10">
                    @Html.DropDownList("CountryList",new SelectList(ViewBag.CountryList),new {@class = "form-control" })
                </div>
            </div>
    
            
        </div>
    }
    
    
    In the preceding code snippet we are binding DropDownList with ViewBag in which country list is assigned into the controller class.
    Step 4: Run application
     Now run the application we will see dropdownlist having list of countries as shown in the following screen shot


    Now Expand dropdownlist to see the other counties as shown in the following screen shot


    I hope from all the preceding examples,  you learned how to display country list without Database in ASP.NET MVC.
    Note:
    • Perform changes in code as per your requirement  its just example .
    • Follow proper standards which might be not meet with this given code.
    • It will not display all county list but its shows list major around 144 countries .
    Summary
    I hope this article is useful for all readers, If you have a suggestion then please contact me.
    Don't Forget To 

    Hosting ASP.NET MVC Application On IIS

    In my previous articles we have learned how to create MVC application and how to publish ASP.NET MVC application, Now in this article we will learn how to host ASP.NET MVC application on IIS . Hosting is required to make any application accessible to the end-user publicly on web. So, in this article, we will learn how to host ASP.NET  MVC application in IIS 10. The following steps are required to host any application.
    If you don't know how to develop and publish ASP.NET MVC application then please refer to following step by step tutorial link to learn about it.
    I hope you have learned required two steps that is developing and publishing ASP.NET MVC application, Now lets start hosting MVC application on IIS.

    Move the published code on Hosting Server
     
    Copy the "Published files" which we have seen in our previous article Publishing ASP.NET MVC Application Using File System and paste those on respective Servers where you want to host the ASP.NET MVC application. In our last article we have published ASP.NET MVC application in the E drive of my Server, as shown in the following image .



    Open IIS Manager
     
    Now, open the IIS Manager from Windows menu or in any other ways you have known.
     

    The above image is of IIS 10 Manager of my Windows 10 machine. The view as well as options might be different on your machine depending on the OS version.
     
    Add Website to host MVC application

    Right click on "Site" in IIS and click on add new website, as shown in the following screenshot.


    After clicking on "Add Website" option, it displays the following configuration window.
     
     
    I hope you understood the preceding configuration by highlighted text.
     
    Define Site Name & Application Pool
     
    Define the site name which will be useful to uniquely identify the site within the IIS server. After specifying the site name, choose the application pool from available pools. You can even create a custom application pool with any desired name. Currently, our IIS manager has the following application Pools.


    Choose the application pool depending on your application configuration. In this article, we are going to choose DefaultAppPool.
    Browse and select Published Folder path
    Now, choose the physical location of published code files by clicking on "Browse" button, as shown in the following image. 
     
     
     
    Now, click on "OK" button.
     
    Define IP address & Port
     
    Choose one IP address from the list of available IP addresses and define the unique port number for the application, which will be unique within the defined IP address.

    Choose Protocol & Host name (optional )
     
    Choose the protocol for your application i.e HTTP or HTTPS which requires port 443 to be open and choose the Host name which will be used publicly to access the application. After defining all the configurations, the web site configuration window will look like this.

    Now, click on OK button. It will create and add the application in IIS.
    Browse the application using web browser
    Browse the hosted application using your system (PC/Laptop) browser , Click on browse hyperlink which is  highlighted in the following image 
     

    After clicking on preceding IIS shown image browse hyperlink, then application will open in your default web browser as shown in the following image
     
     
     
    Preceding is our IIS hosted ASP.NET MVC application which is running in browser.

    Note
    • This article is just guideline to show how to host ASP.NET MVC web API application on IIS .
    • Optimize the speed by setting debug as false etc., from web.config file as per your skills. 
    • In this article, the optimization is not covered in depth.
    • Configure the authentication in IIS as per your requirement .
    Summary
    I hope, this article is useful for all the readers to learn about hosting ASP.NET MVC web application on IIS. If you have any suggestions, please contact me.

    Don't Forget To 

    www.CodeNirvana.in

    Protected by Copyscape Online Copyright Protection
    Copyright © Compile Mode