I have a MVC Project and Web API project both separately ,each time i want to consume a web api method from MVC i have to provide the path of the web api method..So my question is is there any process where I will keep all the url of all the web api methods
in MVC project.
Should I use two different projects or else I should use one MVC project only.
The projects should be two projects in the same solution.
You can make a folder in the MVC project call it ServiceLayer, and the MVC controller will make calls to the WebAPI service using HTTPClient(). with classes in the ServiceLayer.
CRUD for database using Entity Framework sitting behind the WebAPI.
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 ServiceLayer
{
public class AuthorSvc :IAuthorSvc
{
public List<DtoAuthor> GetAll()
{
var dtoauthors = new List<DtoAuthor>();
using (var client = new HttpClient())
{
var uri = new Uri("http://localhost:8081/author/GetAll");
var response = client.GetAsync(uri).Result;
if (!response.IsSuccessStatusCode)
throw new Exception(response.ToString());
var responseContent = response.Content;
var responseString = responseContent.ReadAsStringAsync().Result;
dynamic authors = JArray.Parse(responseString) as JArray;
foreach (var obj in authors)
{
DtoAuthor dto = obj.ToObject<DtoAuthor>();
dtoauthors.Add(dto);
}
}
return dtoauthors;
}
public List<DtoAuthorType> GetAuthorTypes()
{
var dtoauthortypes = new List<DtoAuthorType>();
using (var client = new HttpClient())
{
var uri = new Uri("http://localhost:8081/author/GetAuthorTypes");
var response = client.GetAsync(uri).Result;
if (!response.IsSuccessStatusCode)
throw new Exception(response.ToString());
var responseContent = response.Content;
var responseString = responseContent.ReadAsStringAsync().Result;
dynamic authortypes = JArray.Parse(responseString) as JArray;
foreach (var obj in authortypes)
{
DtoAuthorType dto = obj.ToObject<DtoAuthorType>();
dtoauthortypes.Add(dto);
}
}
return dtoauthortypes;
}
public DtoAuthor Find(int id)
{
DtoAuthor dto;
using (var client = new HttpClient())
{
var uri = new Uri("http://localhost:8081/author/Find?id=" + id);
HttpResponseMessage getResponseMessage = client.GetAsync(uri).Result;
if (!getResponseMessage.IsSuccessStatusCode)
throw new Exception(getResponseMessage.ToString());
var responsemessage = getResponseMessage.Content.ReadAsStringAsync().Result;
dynamic author = JsonConvert.DeserializeObject(responsemessage);
dto = author.ToObject<DtoAuthor>();
}
return dto;
}
public void Add(DtoAuthor dto)
{
using (var client = new HttpClient { BaseAddress = new Uri("http://localhost:8081") })
{
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("/author/Add", inputMessage.Content).Result;
if (!message.IsSuccessStatusCode)
throw new Exception(message.ToString());
}
}
public void Update(DtoAuthor dto)
{
using (var client = new HttpClient { BaseAddress = new Uri("http://localhost:8081") })
{
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("/author/Update", inputMessage.Content).Result;
if (!message.IsSuccessStatusCode)
throw new Exception(message.ToString());
}
}
public void Delete(DtoId dto)
{
using (var client = new HttpClient { BaseAddress = new Uri("http://localhost:8081") })
{
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("/author/Delete", inputMessage.Content).Result;
if (!message.IsSuccessStatusCode)
throw new Exception(message.ToString());
}
}
}
}
If you find the post has answered your issue, then please mark post as 'answered'.
In above code all the wep api urls are hard-coded suppose i have "n" numbers of web apis so where should I put all these web api url for loose coupling.
In above code all the wep api urls are hard-coded suppose i have "n" numbers of web apis so where should I put all these web api url for loose coupling.
You can put them in the appsettings.json or Web.config file and try to read them. I have never seen it done for a WebAPI solution. I have seen it done for WCF Web Service, because the WCF client program end point address of the service is in the client's
config file.
If you find the post has answered your issue, then please mark post as 'answered'.
Member
15 Points
40 Posts
Store WebAPI URL in MVC Project
Feb 24, 2020 06:59 AM|Mrutyunjaya|LINK
Hi All,
I have a MVC Project and Web API project both separately ,each time i want to consume a web api method from MVC i have to provide the path of the web api method..So my question is is there any process where I will keep all the url of all the web api methods in MVC project.
Should I use two different projects or else I should use one MVC project only.
Just needed the best approach to implement.
Thanks in Advance..
Contributor
4923 Points
4198 Posts
Re: Store WebAPI URL in MVC Project
Feb 24, 2020 07:36 AM|DA924|LINK
The projects should be two projects in the same solution.
You can make a folder in the MVC project call it ServiceLayer, and the MVC controller will make calls to the WebAPI service using HTTPClient(). with classes in the ServiceLayer.
https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8
CRUD for database using Entity Framework sitting behind the WebAPI.
Member
15 Points
40 Posts
Re: Store WebAPI URL in MVC Project
Feb 24, 2020 07:52 AM|Mrutyunjaya|LINK
Hi,
Thanks for your reply.
In above code all the wep api urls are hard-coded suppose i have "n" numbers of web apis so where should I put all these web api url for loose coupling.
Contributor
4923 Points
4198 Posts
Re: Store WebAPI URL in MVC Project
Feb 24, 2020 02:13 PM|DA924|LINK
You can put them in the appsettings.json or Web.config file and try to read them. I have never seen it done for a WebAPI solution. I have seen it done for WCF Web Service, because the WCF client program end point address of the service is in the client's config file.