Calling Web API from MVC controller

前端 未结 5 1272
余生分开走
余生分开走 2021-02-01 03:37

I have a WebAPI Controller within my MVC5 project solution. The WebAPI has a method which returns all files in a specific folder as a Json list:

[{\"name\":\"file

5条回答
  •  滥情空心
    2021-02-01 04:15

    Its very late here but thought to share below code. If we have our WebApi as a different project altogether in the same solution then we can call the same from MVC controller like below

    public class ProductsController : Controller
        {
            // GET: Products
            public async Task Index()
            {
                string apiUrl = "http://localhost:58764/api/values";
    
                using (HttpClient client=new HttpClient())
                {
                    client.BaseAddress = new Uri(apiUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage response = await client.GetAsync(apiUrl);
                    if (response.IsSuccessStatusCode)
                    {
                        var data = await response.Content.ReadAsStringAsync();
                        var table = Newtonsoft.Json.JsonConvert.DeserializeObject(data);
    
                    }
    
    
                }
                return View();
    
            }
        }
    

提交回复
热议问题