Creating an MVC Proxy for the Web API Controller

I have an MVC project that displays outside. I have an internal web API project.

For reasons beyond my control, I cannot open a web API project directly, and I cannot add web API controllers to my MVC project.

I need to create an MVC controller that will act as a proxy for the Web API controller. I need an answer from MVC Controller to look as if the API were being called directly.

What is the best way to do this?

Is there a better approach than mine so far?

How can I fix the error I get?

Here is what I still have:

Mymvccontroller

[HttpGet] public HttpResponseMessage GetData(HttpRequestMessage request) { ... var response = proxy.GetData(); return request.CreateResponse(); } 

Myproxyclass

 public HttpResponseMessage GetData() { ... return HttpRequest(new HttpRequestMessage(HttpMethod.Get, uri)); } private HttpResponseMessage HttpRequest(HttpRequestMessage message) { HttpResponseMessage response; ... using (var client = new HttpClient()) { client.Timeout = TimeSpan.FromSeconds(120); response = client.SendAsync(message).Result; } return response; } 

In the MVC controller, I get an InvalidOperationException in the request.CreateResponse () line. The error says:

The request does not have a configuration object associated with it, or the provided configuration is null.

Any help would be greatly appreciated. I searched Google and StackOverflow, but I could not find a good solution to create this proxy between MVC and web API.

Thanks!

+6
source share
1 answer

You can do this by simply creating a JsonResult action in your controller that returns the result of the web API call.

 public class HomeController : Controller { public async Task<JsonResult> CallToWebApi() { return this.Content( await new WebApiCaller().GetObjectsAsync(), "application/json" ); } } public class WebApiCaller { readonly string uri = "your url"; public async Task<string> GetObjectsAsync() { using (HttpClient httpClient = new HttpClient()) { return await httpClient.GetStringAsync(uri); } } } 
+3
source

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


All Articles