Consuming web API from MVC4 controller?

I am currently working on a website and I had a good separation of problems by repository template with repositories and managers. Now I'm trying to implement a web API, as I would greatly benefit from it in the future, being able to use it from different clients. Since I'm fairly new to REST services, I am having problems with the correct procedure to use my web API from the Service in my MVC4 application, then to use this service in my MVC controllers. I do not want to use knockout for every API call.

My web interfaces look something like this:

public class UserController : ApiController { private readonly IUserManager _manager; public UserController(IUserManager manager) { this._manager = manager; } // GET api/user public IEnumerable<User> Get() { return _manager.GetAll(); } // GET api/user/5 public User Get(int id) { return _manager.GetById(id); } // POST api/user public void Post(User user) { _manager.Add(user); } // PUT api/user/5 public void Put(User user) { _manager.Update(user); } // DELETE api/user/5 public void Delete(User user) { _manager.Delete(user); } } 

I would like to create a service to use my web API as such:

 public class UserService : IUserService { ....Implement something to get,post,put,and delete using the api. } 

so I can use it in my mvc controller:

 public class UserController: Controller { private readonly IUserService _userService; public UserController(IUserService userService) { this._userService = userService; } //And then I will be able to communicate with my WebAPI from my MVC controller } 

I know that this is possible because I saw this in some workplaces, but it is very difficult to find articles about it, I only found articles explaining how to use the web API via knockout. Any help or advice would be appreciated.

+4
source share
2 answers

Take a look at the implementation here: https://github.com/NBusy/NBusy.SDK/blob/master/src/NBusy.Client/Resources/Messages.cs

Mostly the HttpClient class is HttpClient to use the Web API. However, one caveat, all responses are wrapped in a custom HttpResponse class in this example. You do not need to do this and simply use the extracted DTO object as the return type or the raw HttpResponseMessage class.

+1
source

You might want to create a static class, I created a separate class library for use in solutions that can use the API.

NOTE. I use RestSharp to work POST and PUT, since I could not get them to work using regular HttpClient over SSL. As you can see, this is described in question .

 internal static class Container { private static bool isInitialized; internal static HttpClient Client { get; set; } internal static RestClient RestClient { get; set; } /// <summary> /// Verifies the initialized. /// </summary> /// <param name="throwException">if set to <c>true</c> [throw exception].</param> /// <returns> /// <c>true</c> if it has been initialized; otherwise, <c>false</c>. /// </returns> /// <exception cref="System.InvalidOperationException">Service must be initialized first.</exception> internal static bool VerifyInitialized(bool throwException = true) { if (!isInitialized) { if (throwException) { throw new InvalidOperationException("Service must be initialized first."); } } return true; } /// <summary> /// Initializes the Service communication, all methods throw a System.InvalidOperationException if it hasn't been initialized. /// </summary> /// <param name="url">The URL.</param> /// <param name="connectionUserName">Name of the connection user.</param> /// <param name="connectionPassword">The connection password.</param> internal static void Initialize(string url, string connectionUserName, string connectionPassword) { RestClient = new RestClient(url); if (connectionUserName != null && connectionPassword != null) { HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential(connectionUserName, connectionPassword) }; Client = new HttpClient(handler); RestClient.Authenticator = new HttpBasicAuthenticator(connectionUserName, connectionPassword); } else { Client = new HttpClient(); } Client.BaseAddress = new Uri(url); isInitialized = true; } } public static class UserService { public static void Initialize(string url = "https://serverUrl/", string connectionUserName = null, string connectionPassword = null) { Container.Initialize(url, connectionUserName, connectionPassword); } public static async Task<IEnumerable<User>> GetServiceSites() { // RestSharp example Container.VerifyInitialized(); var request = new RestRequest("api/Users", Method.GET); request.RequestFormat = DataFormat.Json; var response = await Task.Factory.StartNew(() => { return Container.RestClient.Execute<List<User>>(request); }).ConfigureAwait(false); return response.Data; // HttpClient example var response = await Container.Client.GetAsync("api/Users/").ConfigureAwait(false); return await response.Content.ReadAsAsync<IEnumerable<User>>().ConfigureAwait(false); } public static async Task<User> Get(int id) { Container.VerifyInitialized(); var request = new RestRequest("api/Users/" + id, Method.GET); var response = await Task.Factory.StartNew(() => { return Container.RestClient.Execute<User>(request); }).ConfigureAwait(false); return response.Data; } public static async Task Put(int id, User user) { Container.VerifyInitialized(); var request = new RestRequest("api/Users/" + id, Method.PATCH); request.RequestFormat = DataFormat.Json; request.AddBody(user); var response = await Task.Factory.StartNew(() => { return Container.RestClient.Execute(request); }).ConfigureAwait(false); } public static async Task Post(User user) { Container.VerifyInitialized(); var request = new RestRequest("api/Users", Method.POST); request.RequestFormat = DataFormat.Json; request.AddBody(user); var response = await Task.Factory.StartNew(() => { return Container.RestClient.Execute(request); }).ConfigureAwait(false); } public static async Task Delete(int id) { Container.VerifyInitialized(); var request = new RestRequest("api/Users/" + id, Method.DELETE); var response = await Task.Factory.StartNew(() => { return Container.RestClient.Execute(request); }).ConfigureAwait(false); } } 
+1
source

Source: https://habr.com/ru/post/1495158/


All Articles