C# Web API – Using Web API Proxy

cweb-api

I have a MVC application and a web api. The Web api contain all business logic and the mvc controller has only ui logic.

I want build a web api proxy but I don't know if it's a good idea.

With the web api proxy The controller is decoupled from the name of the action in the web api and from the verbs and dto used in the web api. With one code row, I call the web api and i receive a response.
If i want call the action in many controller, i have to use only one line of code and if there is a change, i change only the proxy.

Without proxy It's simpler, because in the controller I use httpclient for calling the web api, but if a want call the same action from many controller mvc, i have to replicate the code.

The proxy I want create is registered with autofac in the global asax, and in the controller constructor i inject the proxy.

For example if i want a list of prople, with proxy I have to
Register the PeopleProxy in the global asax
create the constructor of the mvc controller with the IProxyPeople

private IProxyPeople peopleProxy;
MyController(IProxyPeople peopleProxy){
    this.peopleProxy = peopleProxy;
}

Call with a code like

peopleProxy.GetPeople()

Without proxy

I call the web apri directly from mvc controller with code like

using (HttpClient client = CreateHttpClient())
{
    var peoples;
    try
    {
        HttpResponseMessage result = client.GetAsync("api/People").Result;
        peoples = result.Content.ReadAsAsync<List<People>>().Result;
    }
    catch (Exception exc)
    {
         CLog.LogError(exc);
    }                   
}

Someone thinks that it's better call the web api directly from the controller because is more simpler than create the proxy and there aren't overhead with autofac.
Should be a good idea create a web api proxy?

Best Answer

The service (proxy) doesn't just abstract the endpoint, it also encapsulates the response parsing and error handling logic. It's a good abstraction.

It's my experience that people who argue for inlining code and shun abstraction have not yet gathered enough experience to know how that behavior will burn them later. Do it your way.

Related Topic