European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: Swagger For .NET Core MVC Web API

clock February 14, 2022 07:26 by author Peter

Swagger (OpenAPI) is a language-agnostic specification for describing REST APIs. It allows both computers and humans to understand the capabilities of a REST API without direct access to the source code. Swagger UI offers a web-based UI that provides information about the service, using the generated OpenAPI specification. Swagger UI is an alternative to Postman.

I used Swagger more than several times in my articles, but just as a minor tool used in different topics. When I tried to get info of Swagger, I had to search from these articles, which were not convinient. So, I rewrite these two articles, especially about Swagger for .NET MVC Web API or .NET Core MVC Web API.

If we created a new .NET Core 5.0 Web API project, the Swagger cient for Web API would be installed by default. In our current case, although we use .NET Core 5.0, the Web API is created in a MVC module, so we need to install Swagger manually. This way will work for the .NET Core version before 5.0.

This article is part of my another article: Consume Web API By MVC In .NET Core (1), Server And Framework, we got Swagger related part here. You can see details from there.
Step 1 - Create an ASP.NET Core MVC application

We use the version of Visual Studio 2019 16.8 and .NET 5.0 SDK to build the app.

    Start Visual Studio and select Create a new project.
    In the Create a new project dialog, select ASP.NET Core Web Application > Next.
    In the Configure your new project dialog, enter MVCCallWebAPI for Project name.
    Select Create.
    In the Create a new ASP.NET Core web application dialog, select,
     
        .NET Core and ASP.NET Core 5.0 in the dropdowns.
        ASP.NET Core Web App (Model-View-Controller).
        Create

Build and run the app, you will see the following image shows the app,


Step 2~3 - Scaffold API Controller with Action using Entity Framework

Please see the article, Consume Web API By MVC In .NET Core (1), Server And Framework,
B: Add Web API with Entity Framework Code First

    Step 1: Set up a new Database context
    Step 2: Work with a database using Entity Framework code first appoach.
    Step 3,:Scaffold API Controller with Action using Entity Framework

Step 4 - Add Swagger client for Web API

1. Install Swagger Client
Right-click the project in Solution Explorer > Manage NuGet Packages, search for Swagger

Step 2~3 - Scaffold API Controller with Action using Entity Framework

Please see the article, Consume Web API By MVC In .NET Core (1), Server And Framework,
B: Add Web API with Entity Framework Code First

    Step 1: Set up a new Database context
    Step 2: Work with a database using Entity Framework code first appoach.
    Step 3,:Scaffold API Controller with Action using Entity Framework

Step 4 - Add Swagger client for Web API

1. Install Swagger Client
Right-click the project in Solution Explorer > Manage NuGet Packages, search for Swagger


There are three main components to Swashbuckle (Swagger), we only need to install two of them: SwaggerGen and SwaggerUI, the Swagger would be included.

2.  Register Swagger Client in startup.cs file
Add the Swagger generator to the services collection in the Startup.ConfigureServices method,
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v2", new OpenApiInfo { Title = "MVCCallWebAPI", Version = "v2" });
    });
    ......
}


Enable the middleware for serving the generated JSON document and the Swagger UI, in the Startup.Configure method,
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v2/swagger.json", "MVCCallWebAPI");
    });
    ......
}

Now, we are almost ready to run the app.

Step 5 - Run and Test the app

Before we run the app, modify the header of the file: Views/Shared/_layout.cshtml Views again to add Swagger (line 11~13), shown below,
<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-controller="StoresMVC" asp-action="Index">MVC app</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Swagger" asp-action="Index">Web API</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>

Now, we run the app,


Click Web API, we got the Swagger Client screen,


 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How To Show Dynamic List Using View Bag In ASP.NET MVC?

clock February 2, 2022 08:15 by author Peter

In this blog, we will learn about how we can show the dynamic list using View Bag in ASP.net MVC.

Step 1 - Create a Model
First create the Model and define the public properties of Model.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AspNetMVCPractice.Models {
    public class Employee {
        public int Id {
            get;
            set;
        }
        public string Name {
            get;
            set;
        }
        public string Address {
            get;
            set;
        }
        public string Country {
            get;
            set;
        }
        public string City {
            get;
            set;
        }
        public Department Department {
            get;
            set;
        }
    }
}


Step 2 - Define the Action Method in Controller
public ActionResult Index() {
    return View();
}

Step 3 - Create the List and Pass the Model to that List
The third step is to create the list of Employees inside your Action Method.
public ActionResult Index() {
    List < Employee > list = new List < Employee > () {
        new Employee() {
                Id = 1,
                    Name = "Mudassar",
                    Address = "Amsterdam",
                    City = "Amsterdam Netherlands",
                    Country = "Netherlands"
            },
            new Employee() {
                Id = 2,
                    Name = "Asad",
                    Address = "Amsterdam",
                    City = "Amsterdam Netherlands",
                    Country = "Netherlands"
            },
            new Employee() {
                Id = 3,
                    Name = "Mubashir",
                    Address = "Amsterdam",
                    City = "Amsterdam Netherlands",
                    Country = "Netherlands"
            },
    };
    ViewBag.model = list;
    return View();
}

Step 4 - Pass the List to View bag
Pass the data of list to view bag using model,
List < Employee > list = new List < Employee > () {
    new Employee() {
            Id = 1,
                Name = "Peter",
                Address = "Amsterdam",
                City = "Amsterdam Netherlands",
                Country = "Netherlands"
        },
        new Employee() {
            Id = 2,
                Name = "Jan",
                Address = "Amsterdam",
                City = "Amsterdam Netherlands",
                Country = "Netherlands"
        },
        new Employee() {
            Id = 3,
                Name = "Rudolph",
                Address = "Amsterdam",
                City = "Amsterdam Netherlands",
                Country = "Netherlands"
        },
};
ViewBag.model = list;


Step 5 - Show the Data on Front End
Given below code is to show the dynamic list of data using view bag in asp.net MVC.
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="wrapper">
  <div class="container">
    <table class="table">
      <thead>
        <tr>
          <th scope="col">Id</th>
          <th scope="col">Name</th>
          <th scope="col">Address</th>
          <th scope="col">City</th>
          <th scope="col">Country</th>
        </tr>
      </thead>
      @foreach (var item in ViewBag.model)
       {
      <tbody>
        <tr>
          <th scope="row">@item.Id</th>
          <td>@item.Name</td>
          <td>@item.Address</td>
          <td>@item.City</td>
          <td>@item.Country</td>
        </tr>
      </tbody>             }
    </table>
  </div>
</div>



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Attribute Routing in ASP.Net MVC 5.0

clock January 28, 2022 06:27 by author Peter

Routing is a pattern matching process that monitors the requests and determines what to do with each request. In other words we can say Routing is a mechanism for mapping requests within our MVC application.

When a MVC application starts the first time, the Application_Start () event of global.asax is called. This event registers all routes in the route table using the RouteCollection.MapRoute method.

Example
    routes.MapRoute(  
        "Default", // Route name  
        "{controller}/{action}/{id}", // URL with parameters  
        new { controller = "Home", action = "about", id = UrlParameter.Optional } // Parameter defaults  
    );


MVC 5 supports a new type of routing called “Attribute Routing”. As the name suggests, Attribute Routing enables us to define routing on top of the controller action method.

Enabling Attribute Routing
To enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection class during configuration.
    public class RouteConfig  
    {  
        public static void RegisterRoutes(RouteCollection routes)  
        {  
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
            routes.MapMvcAttributeRoutes();  
        }  
    }


We can also add a customized route within the same method. In this way we can combine Attribute Routing and convention-based routing.
    public class RouteConfig  
    {  
        public static void RegisterRoutes(RouteCollection routes)  
        {  
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
            routes.MapMvcAttributeRoutes();   
            routes.MapRoute(  
                   "Default", // Route name  
                    "{controller}/{action}/{id}", // URL with parameters  
                    new { controller = "Home", action = "about", id = UrlParameter.Optional } // Parameter defaults  
               );  
        }  
    }


Attribute Routing Example
A route attribute is defined on top of an action method. The following is the example of a Route Attribute in which routing is defined where the action method is defined.

In the following example, I am defining the route attribute on top of the action method
    public class HomeController : Controller  
    {  
        //URL: /Mvctest  
        [Route(“Mvctest”)]  
        public ActionResult Index()  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
    }}   

Attribute Routing with Optional Parameter
We can also define an optional parameter in the URL pattern by defining a question mark (“?") to the route parameter. We can also define the default value by using parameter=value.
    public class HomeController : Controller  
    {  
      
      // Optional URI Parameter  
      // URL: /Mvctest/  
      // URL: /Mvctest/0023654  
      
        [Route(“Mvctest /{ customerName ?}”)]  
        public ActionResult OtherTest(string customerName)  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
      
       // Optional URI Parameter with default value  
      // URL: /Mvctest/  
      // URL: /Mvctest/0023654  
      
       [Route(“Mvctest /{ customerName =0036952}”)]  
       public ActionResult OtherTest(string customerName)  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


Route Prefixes
We can also set a common prefix for the entire controller (all action methods within the controller) using the “RoutePrefix” attribute.

Example
    [RoutePrefix(“Mvctest”)]  
    public class HomeController : Controller  
    {  
        // URL: /Mvctest/  
        [Route]  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
      
      // Optional URI Parameter  
      // URL: /Mvctest/  
      // URL: /Mvctest/0023654  
        [Route(“{ customerName }”)]  
        public ActionResult OtherTest(string customerName)  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


When we use a tide (~) sign with the Route attribute, it will override the route prefix.

Example
    [RoutePrefix(“Mvctest”)]  
    public class HomeController : Controller  
    {  
        // URL: /NewMvctest/  
        [Route(“~/NewMVCTest”)]  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


Defining Default Route using Route Attribute
We can also define a Route attribute on top of the controller, to capture the default action method as the parameter.

Example
    [RoutePrefix(“Mvctest”)]  
    [Route(“action=index”)]  
    public class HomeController : Controller  
    {  
        // URL: /Mvctest/  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }   
      
        // URL: /Mvctest/NewMethod  
        public ActionResult NewMethod()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }

Defining Route name
We can also define a name of the route to allow easy URI generation.

Example
    [Route(“Mvctest”,  Name = "myTestURL")]  
    public ActionResult Index()  
    {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
    }


We can generate URI using Url.RouteUrl method.
    <a href="@Url.RouteUrl("mainmenu")">Test URI</a>  

Defining Area
We can define the "Area" name from the controller that belongs to the using RouteArea attribute. If we define the “RouteArea” attribute on top of the controller, we can remove the AreaRegistration class from global.asax.
    [RouteArea(“Test”)]  
    [RoutePrefix(“Mvctest”)]  
    [Route(“action=index”)]  
      
    public class HomeController : Controller  
    {  
        // URL: /Test/Mvctest/  
        public ActionResult Index()  
        {  
            ViewBag.Message = "Welcome to ASP.NET MVC!";  
            return View();  
        }  
    }


Attribute Routing gives us more control over the URIs in our MVC web application. The earlier way of routing (convention-based routing) is fully supported by this version of MVC. We can also use both type of routing in the same project.

    Attribute Routing with Optional Parameter



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Read Data From Excel File And Insert Into Database In ASP.NET MVC

clock January 18, 2022 08:01 by author Peter

I will show you how to connect to a Microsoft Excel workbook using the OLEDB.NET data provider, extract data and then insert it into the database table.

To begin with, we will create an ExcelToDatabase in Home Controller which returns a View. This method will return a View from where we have to upload the excel file. Now we will create another method ExcelToDatabase.  Now if we make a get request then ExcelToDatabase will be called and for post request, ExcelToDatabase will be called. The following is the code to read excel files.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.OleDb;
using System.IO;

namespace ExcelReadData
{
    public class HomeController : Controller
    {
        // GET: ClonePanel
        public ActionResult ExcelToDatabase()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ExcelToDatabase()
        {
            bool result = false;
            ViewBag.data = null;

            if (Request.Files["FileUpload1"].ContentLength > 0)
            {
                string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName).ToLower();
                string query = null;
                string connString = "";

                string[] validFileTypes = { ".xls", ".xlsx" };

                string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/Uploads"), Request.Files["FileUpload1"].FileName);
                if (!Directory.Exists(path1))
                {
                    Directory.CreateDirectory(Server.MapPath("~/Content/Uploads"));
                }
                if (validFileTypes.Contains(extension))
                {
                    if (System.IO.File.Exists(path1))
                    { System.IO.File.Delete(path1); }
                    Request.Files["FileUpload1"].SaveAs(path1);

                    //Connection String to Excel Workbook
                    if (extension.Trim() == ".xls")
                    {
                        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                        result = Service.ImportExceltoDatabase(path1, connString, userId);
                    }
                    else if (extension.Trim() == ".xlsx")
                    {
                        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                        result = Service.ImportExceltoDatabase(path1, connString,userId);
                    }
                }
                else
                {
                    ViewBag.Error = "Please Upload Files in .xls, .xlsx or .csv format";
                }
            }
            if (result)
            {
                ViewBag.data = "Data Import Successfully from excel to database.";
            }
            else
            {
                ViewBag.data = "there is some issue while importing the Data.";
            }
            return View();
        }
    }
}


Here I have created a class Service that contains 1 method ConvertXSLXtoDataTable. The following is the code for the service class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;

namespace ExcelReadData
{
    public class Service : IDisposable
    {
        #region **Private Variables**

        private TestDatabaseEntities _dbContext;

        #region **Constructor**

        public ImportExceltoDatabase()
        {
            _dbContext = new TestDatabaseEntities();
        }
        #endregion

        public bool ImportExceltoDatabase(string strFilePath, string connString)
        {
            bool result = false;
            OleDbConnection oledbConn = new OleDbConnection(connString);
            DataTable dt = new DataTable();
            try
            {
                oledbConn.Open();
                using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn))
                {
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    oleda.SelectCommand = cmd;
                    DataSet ds = new DataSet();
                    oleda.Fill(ds);

                    dt = ds.Tables[0];

                    if (dt.Rows.Count > 0)
                    {
                        table tblObj = new table();
                        foreach (DataRow row in dt.Rows)
                        {
                            tblObj.Name = row["Name"].ToString();
                            tblObj.Name = row["Address"].ToString();
                            tblObj.Salary = (int)row["Salary"];
                            tblObj.Age = (int)row["Age"];
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                result = false;
            }
            finally
            {
                oledbConn.Close();
            }
            return result;
        }
    }
}


Now we have to create a view that contains file upload control and a button. When a request for ExcelToDatabase of Home Controller is made, it will show file upload control with button control. When the user selects a file and presses the button it will make a post request to Home Controller and the ExcelToDatabase method will be called. The following is the Razor View for both requests.
@using (Html.BeginForm("ImportExcel", "ExcelToDB", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table>
        <tr><td>Excel file</td><td><input type="file" id="FileUpload1" name="FileUpload1" /></td></tr>
        <tr><td></td><td><input type="submit" id="Submit" name="Submit" value="Submit" /></td></tr>
        <tr><td></td><td><lable>@(viewbag.data)</lable></td></tr>
    </table>
}



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Removing or Customizing View Engines in MVC

clock January 14, 2022 07:48 by author Peter

In this article, you will learn how to remove or customize View Engines not being used by an application.
If you are not using any view engine like ASPX View Engine, it is better to remove it to improve the performance, it is one of the many MVC performance tuning tips.
 
You might be wondering how it will improve the performance. Let's prove it by creating a new action method in a Home Controller, don't add a view for this action method now.
    public ActionResult Foo()  
    {  
         return View();  
    }   

Now, run the application and try navigating to "http://localhost:1212/Home/Foo". Here is what I received:

In the image above you can see how the MVC runtime is looking for an ASPX View Engine first and then the other view engines, which is still a default behavior.

You can control it from the Global.asax file by taking advantage of ViewEngines.Engines.Clear().

    protected void Application_Start()  
    {  
           ViewEngines.Engines.Clear();  
           ViewEngines.Engines.Add(new RazorViewEngine());  
           AreaRegistration.RegisterAllAreas();  
           WebApiConfig.Register(GlobalConfiguration.Configuration);  
           FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
           RouteConfig.RegisterRoutes(RouteTable.Routes);  
           BundleConfig.RegisterBundles(BundleTable.Bundles);  
           AuthConfig.RegisterAuth();  
     }


I highlighted the newly added code above. Now, run the application; you will see the following:


You will see that the MVC runtime successfully removed the ASPX View Engine but it is still looking for VBHTML Views.

You can also control it by customizing Razor View Engine to use only C# languages, by making some changes here:
    ViewEngines.Engines.Add(new RazorViewEngine());  

I highlighted the portion of code. This is actually calling the RazorViewEngine. RazorViewEngine() method internally that has support for both languages (C# and VB) by default. So, we need to override the default functionality by adding a class by the name "CustomRazorViewEngine" that inherits RazorViewEngine. The best place to add this class file is in the App_Start folder.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    namespace MvcApplication1.App_Start  
    {  
        public class CustomRazorViewEngine : RazorViewEngine  
        {  
            public CustomRazorViewEngine()  
            {  
                base.AreaViewLocationFormats = new string[] {  
                    "~/Areas/{2}/Views/{1}/{0}.cshtml",  
                    "~/Areas/{2}/Views/Shared/{0}.cshtml"  
                };  
                base.AreaMasterLocationFormats = new string[] {  
                    "~/Areas/{2}/Views/{1}/{0}.cshtml",  
                    "~/Areas/{2}/Views/Shared/{0}.cshtml"  
                };  
                base.AreaPartialViewLocationFormats = new string[] {  
                    "~/Areas/{2}/Views/{1}/{0}.cshtml",  
                    "~/Areas/{2}/Views/Shared/{0}.cshtml"  
                };  
                base.ViewLocationFormats = new string[] {  
                    "~/Views/{1}/{0}.cshtml",  
                    "~/Views/Shared/{0}.cshtml"  
                };  
                base.PartialViewLocationFormats = new string[] {  
                    "~/Views/{1}/{0}.cshtml",  
                    "~/Views/Shared/{0}.cshtml"  
                };  
                base.MasterLocationFormats = new string[] {  
                    "~/Views/{1}/{0}.cshtml",  
                    "~/Views/Shared/{0}.cshtml"  
                };  
            }  
        }  
    }

Remember to use the System.Web.Mvc namespace. Now, in the Global.asax file add the following code:
    protected void Application_Start()  
    {  
        ViewEngines.Engines.Clear();  
        //ViewEngines.Engines.Add(new RazorViewEngine());  
        ViewEngines.Engines.Add(new CustomRazorViewEngine());  
        AreaRegistration.RegisterAllAreas();  
        WebApiConfig.Register(GlobalConfiguration.Configuration);  
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
        RouteConfig.RegisterRoutes(RouteTable.Routes);  
        BundleConfig.RegisterBundles(BundleTable.Bundles);  
        AuthConfig.RegisterAuth();  
    }


Remember to use the MvcApplication1.App_Start namespace to bring the class file created above into the Global.asax scope. Now, run the application, you will see the following output:


 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: MVC 4 WEB API .NET 4.5

clock January 5, 2022 08:52 by author Peter

We can expose a Web API from ASP.NET MVC4. It is a new feature from Microsoft. Clients can get data from a Web API in any format such as JSON, XML, JSONP, HTML and etc.

Now in this article, I am going to explain how to create a new Web API application and how to get data in various formats such as I mentioned above.
 
Purpose
HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.
 
The ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. In this tutorial, you will use the ASP.NET Web API to create a web API that returns a list of products.
 
The following are the steps to create a new Web API application in Visual Studio 2011.
 
Step 1: We will create a new project and the project type will be MVC4. See the following image:

Step 2: Now we will select a Web API template from the Project template Dialog window.

Step 3: Now we will create a Customer controller inside the Controller folder and will select an API controller with read/write actions.


Step 4: Now we will add an Entity Data Model for our Database where we have a Customer Table. You can see it in the attached Source code.
Step 5: It's time to modify our CustomerController to fetch and save data. See the code below.

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net.Http;  
    using System.Web.Http;  
    using WEBAPISample45.Models;  
      
    namespace WEBAPISample45.Controllers {  
            public class CustomerController: ApiController {  
                private CompanyDBEntities context = new CompanyDBEntities();  
                // GET /api/customer  
                public IEnumerable < CustomerModel > Get() {  
                    IEnumerable < CustomerModel > list = null;  
                    list = (from c in context.Customers select new CustomerModel { Id = c.Id, Name = c.Name, Salary = (long) c.Salary }  
                        .AsEnumerable < CustomerModel > ();  
                        return list;  
                    }  
                    // GET /api/customer/5  
                    public CustomerModel Get(int id) {  
                        return (from c in context.Customers where c.Id == id select new CustomerModel {  
                            Id = c.Id,  
                                Name = c.Name,  
                                Salary = (long) c.Salary  
                        }).FirstOrDefault < CustomerModel > ();  
                    }  
                    // POST /api/customer  
                    public void Post(CustomerModel customer) {  
                        context.AddToCustomers(new Customer {  
                            Id = customer.Id, Name = customer.Name, Salary =  
                                customer.Salary  
                        });  
                        context.SaveChanges(System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);  
                    }  

                    // PUT /api/customer/5  
                    public void Put(int id, CustomerModel customer) {  
                        var cust = context.Customers.First(c => c.Id == id);  
                        cust.Name = customer.Name;  
                        cust.Salary = customer.Salary;  
                        context.SaveChanges();  
                    }  
                    // DELETE /api/customer/5  
                    public void Delete(int id) {  
                        var cust = context.Customers.First(c => c.Id == id);  
                        context.Customers.DeleteObject(cust);  
                        context.SaveChanges();  
                    }  
                }  
            }

Step 7: Now we will run our application and see the output of the web API. Applications will run on the local server http://localhost:40683/ and you have to add the api/customer to the URL. So now your URL will be http://localhost:40683/api/customer. 


If you want to access a customer by id then you can use http://localhost:40683/api/customer/1 as the URL.

Now I am going to discuss a very important thing here. In the Web API, whatever format we use to send a request is the format of the returned response.
In the following JavaScript code, we are requesting data in JSON format. So the response will be returned in the JSON format. I will explain via Fiddler.

    <script type="text/javascript">  
        $(document).ready(function () {  
            $.ajax({  
      
                type: "GET",  
                url: "api/customer/1",  
                dataType: "json",  
                success: function (data) {  
                         alert(data);  
                }  
            });  
        });  
    </script>

XML
    <script type="text/javascript">  
        $(document).ready(function () {  
            $.ajax({  
      
                type: "GET",  
                url: "api/customer/1",  
                dataType: "xml",  
                success: function (data) {  
                         alert(data);  
                }  
            });  
        });  
    </script>


HTML

    <script type="text/javascript">  
        $(document).ready(function () {  
            $.ajax({  
      
                type: "GET",  
                url: "api/customer/1",  
                dataType: "html",  
                success: function (data) {  
                         alert(data);  
                }  
            });  
        });  
    </script>


If you see the above jQuery code we are only changing the DataType and we are not changing anything inside the Web API.
 
Now we will open Fiddler and see how we can get data in various formats.
 
Open Fiddler and go to the Composer tab. See the following screen:

In the above image, you will see the "Accept: text/html, text/html, */*; q=0.01" when we execute the query it will return a response in HTML format.

Now we will change the datatype to XML "Accept: application/xml, text/xml, */*; q=0.01" and will see the output in XML format.

Now we will change the datatype to JSON "Accept: application/json, text/javascript, */*; q=0.01"

And the output is in JSON format:




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Upload Files In ASP.NET MVC 5

clock December 17, 2021 08:38 by author Peter

Creating MVC Application
Let us implement these in a sample Application. Open Visual Studio. Go to File->New->Project. Give a suitable name to the Application. Click OK.

Select MVC Template. Click OK.

Adding Folder
We will add a folder to store the files in the application. Here, I have added a folder in the application.

Adding Controller
Let us add a controller. Right click on the Controller. Add->Controller.


Select MVC 5 Controller -Empty. Click Add.

Give a suitable name to the controller.

Write the following code in the controller.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FileUpload.Controllers
{
    public class UploadController: Controller
    {
        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult UploadFile()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            try
            {
                if (file.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(file.FileName);
                    string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
                    file.SaveAs(_path);
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }
        }
    }
}

Adding View
Right click on UploadFileActionResult. Go to Add View.


Select the empty template. Click add.


Write the following code in the View.

@{
    ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { enctype="multipart/form-data"}))
{
    <div>
        @Html.TextBox("file", "", new {  type= "file"}) <br />
        <input type="submit" value="Upload" />
        @ViewBag.Message
    </div>
}

Browse the Application
Let us now run the Application and check if it is working fine or not. Browse the Application.

Click upload. I have debugged the code to verify that the file gets uploaded successfully.


The code is working as per the expectations, as it hits the success message. We should get this message on the View, as well.


We will verify the file uploaded, by opening the folder in the Application’s directory.

Hence, we have just learned how to upload the file in ASP.NET MVC. I hope this post is useful to developers.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How Dapper Has Become King ORM In C#/MVC/.NET/.CORE?

clock December 15, 2021 06:34 by author Peter

What is Dapper?
    Dapper is a popular simple object mapping tool and nothing but an Object Relational Mapping(ORM).
    If you don't want to spend hours writing code to map query results from ADO.NET data readers to instances of those objects, Dapper is very useful for that.
    It not only allows developers to map relational database tables with .NET objects but also allows them to execute SQL queries in the database. It also gives flexibility as they can use tables, stored procedures, and views directly in the databases.

Is Dapper secure?
Dapper is the easiest and most secure way to buy and store all your digital assets from the groundbreaking apps and games powered by Flow. The Metaverse is here.

Is Dapper a micro ORM?
Dapper is a Mini micro ORM or a simple object mapper framework that helps to map the native query output to a domain class or a C# class. It is a high-performance data access system built by the StackOverflow team and released as open-source.
Here you can find all SO-thread

What is the fastest ORM?

I've created one example based on the example result I can say - Dapper is faster than SQL & Entity Framework.

Extension methods
Dapper extends the IDbConnection interface with these various methods,

    Execute
    Query:
    QuerySingle:
    QuerySingleOrDefault:
    QueryFirst:
    QueryFirstOrDefault:
    QueryMultiple:

Note
Here you can find the all the method details - Dapper methods

How does a dapper become a king?
Let's create one short example. Let us have one table “Employee” namely whatever you prefer.

 

Employee table

Column Type
ID Int NOT NULL - PK
Name NVARCHAR (50) NULL
Dob DATE NULL
Mob_no VARCHAR (15) NULL
Salary DECIMAL (18,12) NULL
Is_Approved BIT NULL

Note
In the above table you can see we used almost all data types on a regular basis.

Let’s create a table and fill the 1 Million record in the tables.

Table scripts

CREATE TABLE [dbo].[employee] (
    [Id]          INT           IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (50) NULL,
    [Dob]         DATE          NULL,
    [Mob_no]      VARCHAR (15)  NULL,
    [Salary]      DECIMAL (18,12)  NULL,
    [Is_Approved] BIT           NULL,
    CONSTRAINT [PK_employee] PRIMARY KEY CLUSTERED ([Id] ASC)
);

Using the while loop fill the 1 Million data into the table.

Declare @Name nvarchar(50)
Declare @Dob Date
Declare @Mob_no VARCHAR(15)
Declare @Salary Decimal(18,12)
Declare @Is_Approved bit
DECLARE @counter int = 1


WHILE(@counter <= 1000000)
BEGIN
    SET @Name = CONCAT('Name_',@counter);
    SET @Dob = GETDATE()+@counter;
    SET @Mob_no = CONCAT('12345678_',@counter);
    SET @Salary = (10+@counter)
    SET @Is_Approved = 1

    INSERT INTO employee([Name],[Dob],[Mob_no],[Salary],[Is_Approved]) VALUES (@Name,@Dob,@Mob_no,@Salary,@Is_Approved);
    Set @counter = @counter+1;
END

Note
All records are inserted now to check the table data size.

You can check your table size using this store procedure.

exec sp_spaceused ‘employee’

SQL

Here you can see almost 67MB of data present in the table.

Another way you can find the storage of the data using an SQL server.

Steps
    Open your SQL Server
    Navigate you're working database
    Expand your tables folder -> Right-click on your table -> Click on properties menu at the last.
    Below popup is visible

*Let’s create a sample application

//Employee Class
public partial class employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<System.DateTime> Dob { get; set; }
        public string Mob_no { get; set; }
        public Nullable<decimal> Salary { get; set; }
        public Nullable<bool> Is_Approved { get; set; }
    }

//Home Controller
public class HomeController: Controller
    {
        private readonly string _connectionString = "{YOUR_CONNECTION}";
        SqlConnection con;
        SqlDataAdapter da;
        DataSet ds = new DataSet();
        List<employee> emp = new List<employee>();
        private demo_databaseEntities dd = new demo_databaseEntities();

        public ActionResult SQL()
        {
            Debug.Write("\nSQL Process Start => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            con = new SqlConnection(_connectionString);
            da = new SqlDataAdapter("select * from employee", con);
            da.Fill(ds);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                emp.Add(new employee()
                {
                    Id = Convert.ToInt32(dr["Id"]),
                    Name = Convert.ToString(dr["Name"]),
                    Dob = Convert.ToDateTime(dr["Dob"]),
                    Mob_no = Convert.ToString(dr["Mob_no"]),
                    Salary = Convert.ToDecimal(dr["Salary"]),
                    Is_Approved = Convert.ToBoolean(dr["Is_Approved"])
                });

            }
            Debug.Write("\nSQL Process End => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            //Some process for paging
            return Json(new { count = emp.Count(), data = emp.Take(10000)}, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Dapper()
        {
            Debug.Write("\nDapper Process Start => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            con = new SqlConnection(_connectionString);
            emp = con.Query<employee>("select * from employee").ToList();
            Debug.Write("\nDapper Process End => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            //Some process for paging
            return Json(new { count = emp.Count(), data = emp.Take(10000) }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult EntityFramework()
        {
            Debug.Write("\nEF Process Start => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            emp = dd.employees.ToList();
            Debug.Write("\nEF Process End => " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
            //Some process for paging
            return Json(new { count = emp.Count(), data = emp.Take(10000) }, JsonRequestBehavior.AllowGet);
        }
    }
*SQL


*Dapper


*Entity Framework




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Creating AutoComplete TextBox In ASP.NET MVC 5

clock December 8, 2021 08:20 by author Peter

One year back I wrote the following article: Creating AutoComplete Extender using ASP.NET  which has huge response. Currently it has 32 k views. So by considering same requirement in ASP.NET MVC I decided to write same type of article using ASP.NET MVC with the help of jQuery UI library. So let us implement this requirement step by step,

Step 1 - Create an ASP.NET MVC Application.
    "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
    "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.
    Choose MVC empty application option and click on OK

Step 2 - Add model class.

Right click on Model folder in the created MVC application and add class named City and right the following line of code,

City.cs
    public class City  
      {  
          public int Id { get; set; }  
          public string Name { get; set; }  
      
      }


Step 3 Add user and admin controller
Right click on Controller folder in the created MVC application and add the controller class as,

Now after selecting controller template, click on add button then the following window appears,

Specify the controller name and click on add button, Now open the HomeController.cs file and write the following code into the Home controller class to bind and create the generic list from model class as in the following,

HomeController.cs
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web.Mvc;  
    using AutoCompleteInMVCJson.Models;  
    namespace AutoCompleteInMVCJson.Controllers  
    {  
        public class HomeController : Controller  
        {  
            // GET: Home  
            [HttpGet]  
            public ActionResult Index()  
            {  
                return View();  
            }  
            [HttpPost]  
            public JsonResult Index(string Prefix)  
            {  
                //Note : you can bind same list from database  
                List<City> ObjList = new List<City>()  
                {  
      
                    new City {Id=1,Name="Latur" },  
                    new City {Id=2,Name="Mumbai" },  
                    new City {Id=3,Name="Pune" },  
                    new City {Id=4,Name="Delhi" },  
                    new City {Id=5,Name="Dehradun" },  
                    new City {Id=6,Name="Noida" },  
                    new City {Id=7,Name="New Delhi" }  
      
            };  
                //Searching records from list using LINQ query  
                var Name = (from N in ObjList  
                                where N.Name.StartsWith(Prefix)  
                              select new { N.Name});  
                return Json(Name, JsonRequestBehavior.AllowGet);  
            }  
        }  
    }

In the above code, instead of going to database for records we are creating the generic list from model class and we will fetch records from above generic list.

Step 4
Reference jQuery UI css and js library reference as there are many ways to add the reference of jQuery library into the our project. The following are some methods:

    Using NuGet package manager , you can install library and reference into the project
    Use CDN library provided by Microsoft, jQuery, Google or any other which requires active internet connection.
    Download jQuery files from jQuery official website and reference into the project.

In this example we will use jQuery CDN library.

Step 5
Create jQuery Ajax function to call controller JSON action method and invoke autocomplete function,
    $(document).ready(function () {  
           $("#Name").autocomplete({  
               source: function(request,response) {  
                   $.ajax({  
                       url: "/Home/Index",  
                       type: "POST",  
                       dataType: "json",  
                       data: { Prefix: request.term },  
                       success: function (data) {  
                           response($.map(data, function (item) {  
                               return { label: item.Name, value: item.Name};  
                           }))  
      
                       }  
                   })  
               },  
               messages: {  
                   noResults: "", results: ""  
               }  
           });  
       })


To work above function don't forget to add the reference of the following jQuery CDN library as,
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">  
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>  
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Step 6
Add view named index and put above json function into the view. After adding code necessary files and logic the Index.cshtml will look like the following,

Index.cshtml
    @model AutoCompleteInMVCJson.Models.City  
    @{    
        ViewBag.Title = "www.hostforlife.eu";    
    }    
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">    
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>    
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>    
    <script type="text/javascript">    
        $(document).ready(function () {    
            $("#Name").autocomplete({    
                source: function (request, response) {    
                    $.ajax({    
                        url: "/Home/Index",    
                        type: "POST",    
                        dataType: "json",    
                        data: { Prefix: request.term },    
                        success: function (data) {    
                            response($.map(data, function (item) {    
                                return { label: item.Name, value: item.Name};    
                            }))    
        
                        }    
                    })    
                },    
                messages: {    
                    noResults: "", results: ""    
                }    
            });    
        })    
    </script>    
    @using (Html.BeginForm())    
    {    
        @Html.AntiForgeryToken()    
        
        <div class="form-horizontal">    
        
            <hr />    
        
            <div class="form-group">    
        
                <div class="col-md-12">    
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })    
        
                </div>    
            </div>    
        
        </div>    
    }    


Now run the application and type any word then it will auto populate the records which exactly start with first word as in the following screenshot,

If you want to auto populate the records which contain any typed alphabet,then just change the LINQ query as contain. Now type any word it will search as follows,

From all the above examples, I hope you learned how to create the auto complete textbox using jQuery UI in ASP.NET MVC.

Note

    For the detailed code, please download the sample zip file.
    Perform changes in Web.config file as per your server location.
    You need to use the jQuery library.

For all the examples above, we learned how to use jQuery UI to create auto complete textbox in ASP.NET MVC. I hope this article is useful for all readers. If you have a suggestion then please contact me.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: OAuth Token Based Authentication In ASP.Net Identity

clock November 30, 2021 06:17 by author Peter

In this article, I will explain how to generate 'Access Token' using credentials of 'Asp.net Identity' in 'ASP.Net MVC. Create a new project in Visual Studio.

Give connection string of your database. Register an Account.

Add the following three Nuget Packages to your project.

  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Cors

Now, add TokenGenerating.cs class in the project.

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;

namespace SecureWebAPI.APIClasses
{
    public class TokenGenerating : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated(); //
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
            var result = userManager.Find(context.UserName, context.Password);
            //UserManager<IdentityUser> userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
            //var result = userManager.Find(context.UserName, context.Password);
            //UserManager holds data for register user.
            //context.UserName = Email of your registered user
            //context.Password = Password of your registered user
            if (result != null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
    }
}

Now add a new startup class for the token configuration file this class holds the information and setting of the token.

using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Threading.Tasks;
using System.Web.Http;

[assembly: OwinStartup(typeof(SecureWebAPI.APIClasses.AuthenticationStartupClass))]

namespace SecureWebAPI.APIClasses
{
    public class AuthenticationStartupClass
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new APIAUTHORIZATIONSERVERPROVIDER();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }
}

Add new class for API Attributes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SecureWebAPI.APIClasses
{
    public class APIAUTHORIZEATTRIBUTE : System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(actionContext);
            }
            else
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
            }
        }
    }
}

Change Global.asax file of your project.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace SecureWebAPI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configuration.EnsureInitialized();
        }
    }
}

Now change your WebApiConfig.cs file routemap

Your Project > App_Start folder > WebApiConfig.cs
routeTemplate: "api/{controller}/{action}/{id}",
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SecureWebAPI.Controllers
{
    public class UserController : ApiController
    {
        [AllowAnonymous]
        [HttpGet]
        public IHttpActionResult Get()
        {
            return Ok("Now server time is: " + DateTime.Now.ToString());
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAuthenticate()
        {
            return Ok("Hello ");
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAdmin()
        {
            return Ok("Helo User");
        }
    }
}

Add a ApiController .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace SecureWebAPI.Controllers
{
    public class UserController : ApiController
    {
        [AllowAnonymous]
        [HttpGet]
        public IHttpActionResult Get()
        {
            return Ok("Now server time is: " + DateTime.Now.ToString());
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAuthenticate()
        {
            return Ok("Hello ");
        }
        [Authorize]
        [HttpGet]
        public IHttpActionResult GetForAdmin()
        {
            return Ok("Helo User");
        }
    }
}

Run your Project and leave it. Open Visual Studio, add a new console project. Add a new class to the console project.
class TokenInfo
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
}

Add function in Program.cs class.
public string GetAccessToken(string Email, string Password)
{
    string AccessToken = "";
    string responseFromServer = "";
    WebRequest request = WebRequest.Create("https://localhost:44370/token"); //your project url
    request.Method = "POST";
    string postData = "username=" + Email + "&password=" + Password + "&grant_type=password";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = byteArray.Length;
    System.IO.Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
    WebResponse response = request.GetResponse();
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    using (dataStream = response.GetResponseStream())
    {
        System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
        responseFromServer = reader.ReadToEnd();
        Console.WriteLine(responseFromServer);
    }
    TokenInfo myDeserializedClass = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenInfo>(responseFromServer);
    AccessToken = myDeserializedClass.access_token;

    response.Close();
    return AccessToken;
}

MainMethod
static void Main(string[] args)
{
    string Email = "Your Registered user Email";
    string Password = "Your Registered user Email";

    Program cls = new Program();
    string AccessToken = cls.GetAccessToken(Email, Password);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://localhost:44370/api/user/GetForAuthenticate"); //Your project Local host api url
    request.AutomaticDecompression = DecompressionMethods.GZip;
    request.Method = "GET";
    request.Headers.Add("Authorization", "Bearer " + AccessToken);
    using (System.Net.WebResponse GetResponse = request.GetResponse())
    {
        using (System.IO.StreamReader streamReader = new System.IO.StreamReader(GetResponse.GetResponseStream()))
        {
            dynamic jsonResponseText = streamReader.ReadToEnd();
        }
    }
    Console.ReadLine();
}

Run console project
If Credential is authenticated then an access token will also be generated.

Keep in mind Your Asp.net MVC project should be running during access token generating.



About HostForLIFE

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

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


Month List

Tag cloud

Sign in