Friday, December 13, 2024

Call to .net core web api

 using System;

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

namespace MesMvc.Util
{
    public static class WebApiClient<T> 
    {
        public static T Query(string url)
        {
            T entity = default(T);

            Func<string, HttpClient, StringContent, HttpResponseMessage> access = (aurl, client, content) =>
            {
                return client.GetAsync(aurl).Result;
            };

            var response = DelegateAccess(url, default(T), access);

            if (response.IsSuccessStatusCode)
            {
                string json = response.Content.ReadAsStringAsync().Result;
                entity = JsonConvert.DeserializeObject<T>(json);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            return entity;
        }

        public static bool Update(string url, T value)
        {
            Func<string, HttpClient, StringContent, HttpResponseMessage> access = (aurl, client, content) => 
            {
                return client.PutAsync(aurl, content).Result;
            };

            return AccessApi(url, value, access);
        }

        public static bool Create(string url, T value)
        {
            Func<string, HttpClient, StringContent, HttpResponseMessage> access = (aurl, client, content) =>
            {
                return client.PostAsync(aurl, content).Result;
            };

            return AccessApi(url, value, access);
        }

        public static bool Delete(string url)
        {
            Func<string, HttpClient, StringContent, HttpResponseMessage> access = (aurl, client, content) =>
            {
                return client.DeleteAsync(aurl).Result;
            };

            return AccessApi(url, default(T), access);
        }

        private static HttpResponseMessage DelegateAccess(string url, T value, Func<string, HttpClient, StringContent, HttpResponseMessage> func)
        {
            HttpClient client = new HttpClient();
            StringContent httpContent = GetContent(value);

            var response = func(url, client, httpContent);

            return response;
        }

        private static bool AccessApi(string url, T value, Func<string, HttpClient, StringContent, HttpResponseMessage> func)
        {
            var response = DelegateAccess(url, value, func);

            return IsResponseOk(response);
        }

        private static StringContent GetContent(T value)
        {
            var json = JsonConvert.SerializeObject(value);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
            return httpContent;
        }

        private static bool IsResponseOk(HttpResponseMessage response)
        {
            if (response.IsSuccessStatusCode)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

MVC controller:
using System;
using System.Collections.Generic;
using System.Linq;
using MesMvc.Models;
using MesMvc.Util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace MesMvc.Controllers
{
    [Authorize]
    [Route("[controller]/[action]")]
    public class EventController : BaseController
    {
        public static string UrlSection = "BusinessUrl:Event";

        public string ServiceUrl { private set; get; }

        public EventController(IConfiguration configuration) : base(configuration) {
            ServiceUrl = Configuration[UrlSection];
        }

        [HttpGet("/Event")]
        public IActionResult GetAll(string sortOrder, string currentFilter, string searchString, int? page, int? PageSize)
        {
            ViewData["IsCellUser"] = IsCellUser;

            ViewData["CurrentSort"] = sortOrder;
            ViewData["PlantCodeSortParm"] = sortOrder == "PlantCode" ? "PlantCode_desc" : "PlantCode";
            ViewData["ProductionCellSortParm"] = sortOrder == "ProductionCell" ? "ProductionCell_desc" : "ProductionCell";
            ViewData["EventNameSortParm"] = sortOrder == "EventName" ? "EventName_desc" : "EventName";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewData["CurrentFilter"] = searchString;

            IEnumerable<EventModel> events = WebApiClient<IEnumerable<EventModel>>.Query(ServiceUrl);

            if (!String.IsNullOrEmpty(searchString))
            {
                events = events.Where(e => !string.IsNullOrEmpty(e.Description) && e.Description.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "PlantCode":
                    events = events.OrderBy(e => e.PlantCode);
                    break;
                case "PlantCode_desc":
                    events = events.OrderByDescending(e => e.PlantCode);
                    break;
                case "ProductionCell":
                    events = events.OrderBy(e => e.ProductionCell);
                    break;
                case "ProductionCell_desc":
                    events = events.OrderByDescending(e => e.ProductionCell);
                    break;
                case "EventName":
                    events = events.OrderBy(e => e.EventName);
                    break;
                case "EventName_desc":
                    events = events.OrderByDescending(e => e.EventName);
                    break;
            }

            return View(PaginatedList<EventModel>.Create(events, page ?? 1, PageSize ?? 5));
        }

        [HttpGet("/Event/Get")]
        public IActionResult GetById([FromQuery] string plantCode, [FromQuery] string productionCell, [FromQuery] string eventName)
        {
            string url = string.Format("{0}/{1}?productionCell={2}&eventName={3}", ServiceUrl, plantCode, productionCell, eventName);
            EventModel item = WebApiClient<EventModel>.Query(url);

            return View(item);
        }

        [HttpGet("/Event/Create")]
        public IActionResult Create()
        {
            ViewBag.Title = "事件";
            ViewBag.SubTitle = "事件-创建";
           // ViewBag.EventClassesList = LoadEventClasses();
            //ViewBag.PlantCodesList = LoadPlantCodes();
            //ViewBag.ProductionCellsList = LoadProductionCells();
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind("PlantCode,ProductionCell,EventName,EventClass,Description,Optional1,Optional2,Optional3,Optional4")] EventModel item)
        {
            if (ModelState.IsValid)
            {
                WebApiClient<EventModel>.Create(ServiceUrl, item);
                return Redirect("/Event");
            }

            //数据模型验证不通过,重新加载页面
            ViewBag.Title = "事件";
            ViewBag.SubTitle = "事件-创建";
            //ViewBag.EventClassesList = LoadEventClasses();
            //ViewBag.PlantCodesList = LoadPlantCodes();
            //ViewBag.ProductionCellsList = LoadProductionCells();

            return View(item);
        }

        [HttpGet("/Event/Update")]
        public IActionResult Update(string PlantCode, string ProductionCell, string EventName)
        {
            ViewBag.Title = "事件";
            ViewBag.SubTitle = "事件-修改";

            string url = string.Format("{0}/{1}?productionCell={2}&eventName={3}", ServiceUrl, PlantCode, ProductionCell, EventName);
            EventModel item = WebApiClient<EventModel>.Query(url);
            if (item == null)
            {
                return NotFound();
            }
            //ViewBag.EventClassesList = LoadEventClasses();
           // ViewBag.PlantCodesList = LoadPlantCodes();
            //ViewBag.ProductionCellsList = LoadProductionCells();
            return View(item);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Update([Bind("PlantCode,ProductionCell,EventName,EventClass,Description,Optional1,Optional2,Optional3,Optional4,RowVersion")] EventModel item)
        {
            ViewBag.Title = "事件";
            ViewBag.SubTitle = "事件-修改";
            if (ModelState.IsValid)
            {
                WebApiClient<EventModel>.Update(ServiceUrl, item);
                return Redirect("/Event");
            }
            //ViewBag.EventClassesList = LoadEventClasses();
            //ViewBag.PlantCodesList = LoadPlantCodes();
            //ViewBag.ProductionCellsList = LoadProductionCells();
            return View(item);
        }

        [HttpGet("/Event/Delete")]
        public IActionResult Delete(string PlantCode, string ProductionCell, string EventName)
        {
            ViewBag.Title = "事件";
            ViewBag.SubTitle = "事件-删除";

            string url = string.Format("{0}/{1}?productionCell={2}&eventName={3}", ServiceUrl, PlantCode, ProductionCell, EventName);
            EventModel item = WebApiClient<EventModel>.Query(url);
            if (item == null)
            {
                return NotFound();
            }
            return View(item);
        }

        // POST: EventClass/Delete
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string PlantCode, string ProductionCell, string EventName)
        {
            string url = string.Format("{0}/{1}?productionCell={2}&eventName={3}", ServiceUrl, PlantCode, ProductionCell, EventName);
            WebApiClient<EventModel>.Delete(url);
            return Redirect("/Event");
        }
    }
}

Web API Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MesWebApi.Business;
using MesWebApi.Models;
using MesWebApi.Util;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MesWebApi.Controllers
{
    [Route("api/[controller]")]
    public class EventController : Controller
    {
        IBusiness<EventModel> _business;

        public EventController(IBusiness<EventModel> business)
        {
            _business = business;
        }

        [HttpGet]
        public IEnumerable<EventModel> GetAll()
        {
            return _business.GetAll();
        }

        [HttpGet("{plantCode}", Name = "GetEvent")]
        public IActionResult GetById(string plantCode, [FromQuery] string productionCell, [FromQuery] string eventName)
        {
            var item = _business.GetById(plantCode, productionCell, eventName);
            if (item == null)
            {
                return NotFound();
            }
            return new ObjectResult(item);
        }

        [HttpPost]
        public IActionResult Create([FromBody] EventModel item)
        {
            if (item == null)
            {
                return BadRequest();
            }

            _business.Create(item);

            return CreatedAtRoute("GetEvent", new { plantCode = item.PlantCode, productionCell = item.ProductionCell, eventName = item.EventName }, item);
        }

        [HttpPut]
        public IActionResult Update([FromBody] EventModel item)
        {
            if (item == null)
            {
                return BadRequest();
            }

            bool isFound = _business.Update(item);

            if (!isFound)
            {
                return NotFound();
            }

            return new NoContentResult();
        }

        [HttpDelete("{plantCode}")]
        public IActionResult Delete(string plantCode, [FromQuery] string productionCell, [FromQuery] string eventName)
        {
            bool isFound = _business.Delete(plantCode, productionCell, eventName);

            if (!isFound)
            {
                return NotFound();
            }

            return new NoContentResult();
        }
    }
}

No comments:

Post a Comment