none
Call WebApi from MVC application and pass the value to a model class

    Pertanyaan

  • I am new to API and MVC.  I have a MVC application which calls a third party Api. The Api returns the data in Json format.

    I want to get the Json data and map it to a class object.


    • Diedit oleh lirodev Selasa, 28 Agustus 2018 14.01
    • Dipindahkan oleh CoolDadTxMVP Selasa, 28 Agustus 2018 17.44 ASP.NET related
    Selasa, 28 Agustus 2018 13.41

Semua Balasan

  • Have you considered json.net

    https://www.newtonsoft.com/json/help/html/DeserializeObject.htm


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Selasa, 28 Agustus 2018 14.02
  • Thanks for the reply Karen.

    Yes I tried deserializing the json string. But it does not work for me.

    I am not sure if it is because I am trying to map only few properties from the json string to my class. I do not want to map the entire JsonString.

    Selasa, 28 Agustus 2018 14.07
  • Your property names match the Json Key names?

    Please refer article below

    https://stackoverflow.com/questions/39170243/how-to-deserialize-json-data-in-mvc

    Selasa, 28 Agustus 2018 14.16
  • This is how you would do it. The WebAPI controller is sending and receiving data with the presentation layer consisting of ASP.NET MVC. The calls to the WebAPI are being called through the model object that the MVC controller uses. Th e Json data is being mapped to a Data Transfer Object.

    ASP.NET can be discussed at the ASP.NET forums.

    http://forums.asp.net/

    using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Entities; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Caching.Memory; using ProgMgmntCore2UserIdentity.WebApi; namespace ProgMgmntCore2UserIdentity.Models { public class ProjectModel : IProjectModel { private readonly IMemoryCache _memoryCache; private readonly IWebApi _webApi; public ProjectModel(IWebApi webApi, IMemoryCache memoryCache) { _memoryCache = memoryCache; _webApi = webApi; } public ProjectViewModels GetProjectsByUserId(string userid) { var vm = new ProjectViewModels {Projects = new List<ProjectViewModels.Project>()}; var dtos = _webApi.GetProjsByUserIdApi(userid).ToList(); vm.Projects.AddRange(dtos.Select(dto => new ProjectViewModels.Project() { ProjectId = dto.ProjectId, ClientName = dto.ClientName, ProjectName = dto.ProjectName, Technology = dto.Technology, ProjectType = dto.ProjectType, StartDate = dto.StartDate, EndDate = dto.EndDate, Cost = dto.Cost }).ToList()); return vm; } public ProjectViewModels.Project GetProjectById(int id) { var responseDto = _webApi.GetProjByIdApi(id); var project = new ProjectViewModels.Project { ProjectId = responseDto.ProjectId, ClientName = responseDto.ClientName, ProjectName = responseDto.ProjectName, Technology = responseDto.Technology, ProjectType = responseDto.ProjectType, StartDate = responseDto.StartDate, EndDate = responseDto.EndDate, Cost = responseDto.Cost }; return project; } public ProjectViewModels.Project Create() { var project = new ProjectViewModels.Project(); return PopulateSelectedList(project); } public void Create(ProjectViewModels.Project project, string userid) { var dto = new DtoProject { ProjectId = project.ProjectId, ClientName = project.ClientName, ProjectName = project.ProjectName, ProjectType = project.ProjectType, Technology = project.Technology, UserId = userid, StartDate = (DateTime) project.StartDate, EndDate = (DateTime) project.EndDate, Cost = (decimal) project.Cost }; _webApi.CreateProjectApi(dto); } public ProjectViewModels.Project Edit(int id) { var responseDto = _webApi.GetProjByIdApi(id); var project = new ProjectViewModels.Project { ProjectId = responseDto.ProjectId, ClientName = responseDto.ClientName, ProjectName = responseDto.ProjectName, Technology = responseDto.Technology, ProjectType = responseDto.ProjectType, StartDate = responseDto.StartDate, EndDate = responseDto.EndDate, Cost = responseDto.Cost }; project = PopulateSelectedList(project); return project; } public void Edit(ProjectViewModels.Project project, string userid) { var dto = new DtoProject { ProjectId = project.ProjectId, ClientName = project.ClientName, ProjectName = project.ProjectName, ProjectType = project.ProjectType, Technology = project.Technology, UserId = userid, StartDate = (DateTime) project.StartDate, EndDate = (DateTime) project.EndDate, Cost = (decimal) project.Cost }; _webApi.UpdateProjectApi(dto); } public void Delete(int id) { _webApi.DeleteProjectApi(new DtoId{Id = id}); } public ProjectViewModels.Project PopulateSelectedList(ProjectViewModels.Project project) { bool isExist = _memoryCache.TryGetValue("DtoCache", out DtoCache dtocache); if (!isExist) { dtocache = _webApi.GetCacheApi(); var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromSeconds(30)); _memoryCache.Set("DtoCache", dtocache, cacheEntryOptions); } project.ProjectTypes = new List<SelectListItem>(); foreach (var pt in dtocache.ProjectTypes) { var sli = new SelectListItem {Value = pt.Value, Text = pt.Text}; project.ProjectTypes.Add(sli); } var selected = (from a in project.ProjectTypes.Where(a => a.Value == project.ProjectType) select a) .SingleOrDefault(); if (selected != null) selected.Selected = true; return project; } } } ============================================= using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using Entities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ProgMgmntCore2UserIdentity.WebApi { public class WebApi : IWebApi { #region ProjectApi public List<DtoProject> GetProjsByUserIdApi(string userid) { var dtoprojects = new List<DtoProject>(); using (var client = new HttpClient()) { var uri = new Uri("http://progmgmntcore2api.com/api/project/GetProjsByUserId?userid=" + userid); var response = client.GetAsync(uri).Result; if (!response.IsSuccessStatusCode) throw new Exception(response.ToString()); var responseContent = response.Content; var responseString = responseContent.ReadAsStringAsync().Result; dynamic projects = JArray.Parse(responseString) as JArray; foreach (var obj in projects) { DtoProject dto = obj.ToObject<DtoProject>(); dtoprojects.Add(dto); } } return dtoprojects; } public DtoProject GetProjByIdApi(int id) { DtoProject dto; using (var client = new HttpClient()) { var uri = new Uri("http://progmgmntcore2api.com/api/project/GetProjById?id=" + id); HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result; if (!getResponseMessage.IsSuccessStatusCode) throw new Exception(getResponseMessage.ToString()); var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result; dynamic project = JsonConvert.DeserializeObject(responsemessage); dto = project.ToObject<DtoProject>(); } return dto; } public void CreateProjectApi(DtoProject dto) { using (var client = new HttpClient { BaseAddress = new Uri("http://progmgmntcore2api.com") }) { string serailizeddto = JsonConvert.SerializeObject(dto); var inputMessage = new HttpRequestMessage { Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json") }; inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage message = client.PostAsync("api/project/CreateProject", inputMessage.Content).Result; if (!message.IsSuccessStatusCode) throw new Exception(message.ToString()); } } public void UpdateProjectApi(DtoProject dto) { using (var client = new HttpClient { BaseAddress = new Uri("http://progmgmntcore2api.com") }) { string serailizeddto = JsonConvert.SerializeObject(dto); var inputMessage = new HttpRequestMessage { Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json") }; inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage message = client.PostAsync("api/project/UpdateProject", inputMessage.Content).Result; if (!message.IsSuccessStatusCode) throw new Exception(message.ToString()); } } public void DeleteProjectApi(DtoId dto) { using (var client = new HttpClient { BaseAddress = new Uri("http://progmgmntcore2api.com") }) { string serailizeddto = JsonConvert.SerializeObject(dto); var inputMessage = new HttpRequestMessage { Content = new StringContent(serailizeddto, Encoding.UTF8, "application/json") }; inputMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage message = client.PostAsync("api/project/DeleteProject", inputMessage.Content).Result; if (!message.IsSuccessStatusCode) throw new Exception(message.ToString()); } } #endregion }

    } =========================== using System; namespace Entities { public class DtoProject { public int ProjectId { get; set; } public string ClientName { get; set; } public string ProjectName { get; set; } public string Technology { get; set; } public string ProjectType { get; set; } public string UserId { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public decimal Cost { get; set; } } }



     

    Selasa, 28 Agustus 2018 17.16
  • Please post questions related to MVC in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Selasa, 28 Agustus 2018 17.44