MVC project practice, in the three-tier architecture to achieve SportsStore-09, ASP. net mvc call ASP. NET Web API query service

Source: Internet
Author: User
Tags representational state transfer

ASP. NET Web API and WCF both reflect the REST software architecture style. In REST, all data is regarded as resources, so it is also a resource-oriented architecture style. All resources can be uniquely identified by Uris. By performing HTTP operations on resources (GET/HEAD, POST, PUT, and DELETE), the resource's characterization status changes, that is, Representational State Transfer, abbreviated as REST.

 

Since 3.5, WCF has also reflected the REST architecture style, but it seems "too heavy" for general message communication. Therefore, Microsoft released ASP. NET Web API, which provides a "lightweight" service and uses MVC to define services in the form of a Controller. The Action method in the Controller corresponds to different HTTP operations.

 

This is the ninth article in the series "Implementing SportsStore in a three-tier architecture", including:

■ 11. ASP. net mvc calls the add, delete, modify, and query service of ASP. NET Web APIs.
□11.1 call the query service
※11.1.1 create an ASP. NET Web API project and introduce Ninject
※11.1.2 provides ASP. net web api addition, deletion, modification, and query services.
※11.1.3 ASP. net mvc calls ASP. net web api query service

 

11. ASP. net mvc calls ASP. NET Web APIs to provide the add, delete, modify, and query service.

11.1 call the query service

11.1.1 create an ASP. NET Web API project and introduce Ninject

In the solution, create an empty "ASP. NET Web API 2 blank project" named "MySportsStore. WebApi ":

 

Add the following reference under MySportsStore. WebApi:
● MySportsStore. BLL
● MySportsStore. IBLL
● MySportsStore. Model
● Install the latest EntityFramework through GuGet
● Install Ninject through NuGet

 

IProductService and its implementation will be used in the Controller to be created. We need to use Ninject to manage interfaces and implementation classes. Under "MySportsStore. WebApi", create a class for the System. Web. Http. Dependencies. IDependencyResolver interface:

using System;using System.Collections.Generic;using System.Web.Http.Dependencies;using Ninject;namespace MySportsStore.WebApi.Extension{    public class NinjectDependencyResolver : IDependencyResolver    {        private List<IDisposable> disposableServices = new List<IDisposable>();        public IKernel Kernel { get; private set; }        public NinjectDependencyResolver(NinjectDependencyResolver parent)        {            this.Kernel = parent.Kernel;        }        public NinjectDependencyResolver()        {            this.Kernel = new StandardKernel();        }        public void Register<TFrom, TTO>() where TTO : TFrom        {            this.Kernel.Bind<TFrom>().To<TTO>();        }        public IDependencyScope BeginScope()        {            return new NinjectDependencyResolver(this);        }        public object GetService(System.Type serviceType)        {            return this.Kernel.TryGet(serviceType);        }        public System.Collections.Generic.IEnumerable<object> GetServices(System.Type serviceType)        {            foreach (var service in this.Kernel.GetAll(serviceType))            {                this.AddDisposableService(service);                yield return service;            }        }        public void Dispose()        {            foreach (IDisposable disposable in disposableServices)            {                disposable.Dispose();            }        }        private void AddDisposableService(object service)        {            IDisposable disposable = service as IDisposable;            if (null != disposable && !disposableServices.Contains(disposable))            {                disposableServices.Add(disposable);            }        }    }}

Then register in the global environment:

using System.Web.Http;using MySportsStore.BLL;using MySportsStore.IBLL;using MySportsStore.WebApi.Extension;namespace MySportsStore.WebApi{    public class WebApiApplication : System.Web.HttpApplication    {        protected void Application_Start()        {            GlobalConfiguration.Configure(WebApiConfig.Register);            NinjectDependencyResolver dependencyResolver = new NinjectDependencyResolver();            dependencyResolver.Register<IProductService, ProductService>();            GlobalConfiguration.Configuration.DependencyResolver = dependencyResolver;        }    }}

 

11.1.2 provides ASP. net web api addition, deletion, modification, and query services

Under "MySportsStore. WebApi", create a ProductApi controller to provide the add, delete, modify, and query service. The implementation is as follows:

Using System; using System. collections. generic; using System. linq; using System. web. http; using MySportsStore. IBLL; using MySportsStore. model; using Ninject; namespace MySportsStore. webApi. controllers {public class ProductApiController: ApiController {[Inject] public IProductService ProductService {get; set;} public ProductApiController () {this. disposableObjects = new List <IDisposable> (); this. addDis PosableObject (ProductService);} // GET api/productapi public IEnumerable <Product> Get () {return ProductService. loadEntities (p => true ). asEnumerable ();} // GET api/productapi/5 public Product Get (int id) {return ProductService. loadEntities (p => p. id = id ). firstOrDefault ();} // POST api/productapi public void Post (Product product) {var dbProduct = ProductService. loadEntities (p => p. id = prod Uct. id ). firstOrDefault (); ProductService. updateEntity (dbProduct);} // PUT api/productapi/5 public void Put (Product product) {ProductService. addEntity (product);} // DELETE api/productapi/5 public void Delete (int id) {var product = ProductService. loadEntities (p => p. id = id ). firstOrDefault (); ProductService. deleteEntity (product) ;}# region manual garbage collection logic protected IList <IDisposable> DisposableObjects {Get; private set;} protected void AddDisposableObject (object obj) {IDisposable disposable = obj as IDisposable; if (disposable! = Null) {this. disposableObjects. add (disposable) ;}} protected override void Dispose (bool disposing) {if (disposing) {foreach (IDisposable obj in this. disposableObjects) {if (null! = Obj) {obj. Dispose () ;}} base. Dispose (disposing) ;}# endregion }}

The above Code uses Ninject to inject IProductService to the ProductService attribute, use ProductService to add, delete, modify, and query, and implement manual garbage collection.


Set "MySportsStore. WebApi" as a startup project and enter: http: // localhost: 1577/api/productapi in the browser

 

The preceding figure shows that AP. net web api queries data services normally. The address here is the unique URI that represents the query status. Through this URI, No matter what language you use, whether it is through the mobile phone client, tablet client, computer client ...... you can call this REST-style service.

 

11.1.3 ASP. net mvc calls ASP. net web api query service

In MVC, HttpClient is used to obtain services of ASP. net web APIs. The following statements query data from ASP. net web APIs asynchronously:

using System.Collections.Generic;using System.Net.Http;using System.Threading.Tasks;using MySportsStore.Model;using Newtonsoft.Json;namespace MySportsStore.WebUI.RESTServices{    public class ProductRESTService    {        readonly string uri = "http://localhost:1577/api/productapi";        public async Task<List<Product>> GetProductsAsync()        {            using (HttpClient httpClient = new HttpClient())            {                return JsonConvert.DeserializeObject<List<Product>>(                    await httpClient.GetStringAsync(uri)                );            }        }     }}

Under "MySportsStore. WebUI", create the Home controller:

using System.Threading.Tasks;using System.Web.Mvc;using MySportsStore.WebUI.RESTServices;namespace MySportsStore.WebUI.Controllers{    public class HomeController : Controller    {        private ProductRESTService service = new ProductRESTService();        public async Task<ActionResult> Index()        {            return View("Index",                await service.GetProductsAsync()            );        }    }}

Under "MySportsStore. WebUI", create the Home/Index. cshtml View:

@ Model IEnumerable <MySportsStore. Model. Product >@{ Layout = null ;}<! DOCTYPE html> 

Set "MySportsStore. WebUI" as the startup project and run:

So far, ASP. net mvc calls the query service of ASP. NET Web APIs.

 

References:
Introduce Ninject, refer to Jiang Jinnan (Artech)'s "IoC application in ASP. NET Web API"

 

The source code is here.

 

The series "MVC project practices, implementing SportsStore in a three-tier architecture" includes:

MVC project practice, under the three-tier architecture to achieve SportsStore-01, EF Code First modeling, DAL layer MVC project practice, under the three-tier architecture to achieve SportsStore-02, DbSession layer, BLL layer MVC project practice, in the three-tier architecture to achieve SportsStore-03, Ninject controller factory MVC project practice, in the three-tier architecture to achieve SportsStore-04, achieve paging MVC project practice, in the three-tier architecture to achieve SportsStore-05, implementation of navigation MVC project practice, in the three-tier architecture to achieve SportsStore-06, to achieve the shopping cart MVC project practice, in the three-tier architecture to achieve SportsStore-07, order submitted MVC project practice, in the three-tier architecture to achieve SportsStore-08, deployment to IIS server MVC project practice, in the three-tier architecture to achieve SportsStore-09, ASP. net mvc calls ASP. NET Web API query service

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.