Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从MVC控制器调用Web API_C#_Asp.net Mvc_Asp.net Web Api - Fatal编程技术网

C# 从MVC控制器调用Web API

C# 从MVC控制器调用Web API,c#,asp.net-mvc,asp.net-web-api,C#,Asp.net Mvc,Asp.net Web Api,我的MVC5项目解决方案中有一个WebAPI控制器。 WebAPI有一种方法,可以将特定文件夹中的所有文件作为Json列表返回: [{“name”:“file1.zip”,“path”:“c:\\”},{…}] 我想从我的HomeController调用此方法,将Json响应转换为List,并将此列表返回到Razor视图。此列表可能为空:[]如果文件夹中没有文件 这是APIController: public class DocumentsController : ApiController {

我的MVC5项目解决方案中有一个WebAPI控制器。 WebAPI有一种方法,可以将特定文件夹中的所有文件作为Json列表返回:

[{“name”:“file1.zip”,“path”:“c:\\”},{…}]

我想从我的HomeController调用此方法,将Json响应转换为
List
,并将此列表返回到Razor视图。此列表可能为空:
[]
如果文件夹中没有文件

这是APIController:

public class DocumentsController : ApiController
{
    #region Methods
    /// <summary>
    /// Get all files in the repository as Json.
    /// </summary>
    /// <returns>Json representation of QDocumentRecord.</returns>
    public HttpResponseMessage GetAllRecords()
    {
      // All code to find the files are here and is working perfectly...

         return new HttpResponseMessage()
         {
             Content = new StringContent(JsonConvert.SerializeObject(listOfFiles), Encoding.UTF8, "application/json")
         };
    }               
}
public class HomeController : Controller
{
     public Index()
     {
      // I want to call APi GetAllFiles and put the result to variable:
      var files = JsonConvert.DeserializeObject<List<QDocumentRecord>>(API return Json);
      }
 }
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var listOfFiles = new DocumentsController().GetAllRecords();
        // OR
        var listOfFiles = new FileListGetter().GetAllRecords();

        return View(listOfFiles);
    }
}
    public JsonResult GetProductsData()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:5136/api/");
            //HTTP GET
            var responseTask = client.GetAsync("product");
            responseTask.Wait();

            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<IList<product>>();
                readTask.Wait();

                var alldata = readTask.Result;

                var rsproduct = from x in alldata
                             select new[]
                             {
                             Convert.ToString(x.pid),
                             Convert.ToString(x.pname),
                             Convert.ToString(x.pprice),
                      };

                return Json(new
                {
                    aaData = rsproduct
                },
    JsonRequestBehavior.AllowGet);


            }
            else //web api sent error response 
            {
                //log response status here..

               var pro = Enumerable.Empty<product>();


                return Json(new
                {
                    aaData = pro
                },
    JsonRequestBehavior.AllowGet);


            }
        }
    }

    public JsonResult InupProduct(string id,string pname, string pprice)
    {
        try
        {

            product obj = new product
            {
                pid = Convert.ToInt32(id),
                pname = pname,
                pprice = Convert.ToDecimal(pprice)
            };



            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5136/api/product");


                if(id=="0")
                {
                    //insert........
                    //HTTP POST
                    var postTask = client.PostAsJsonAsync<product>("product", obj);
                    postTask.Wait();

                    var result = postTask.Result;

                    if (result.IsSuccessStatusCode)
                    {
                        return Json(1, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(0, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    //update........
                    //HTTP POST
                    var postTask = client.PutAsJsonAsync<product>("product", obj);
                    postTask.Wait();
                    var result = postTask.Result;
                    if (result.IsSuccessStatusCode)
                    {
                        return Json(1, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(0, JsonRequestBehavior.AllowGet);
                    }

                }




            }


            /*context.InUPProduct(Convert.ToInt32(id),pname,Convert.ToDecimal(pprice));

            return Json(1, JsonRequestBehavior.AllowGet);*/
        }
        catch (Exception ex)
        {
            return Json(0, JsonRequestBehavior.AllowGet);
        }

    }

    public JsonResult deleteRecord(int ID)
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5136/api/product");

                //HTTP DELETE
                var deleteTask = client.DeleteAsync("product/" + ID);
                deleteTask.Wait();

                var result = deleteTask.Result;
                if (result.IsSuccessStatusCode)
                {

                    return Json(1, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
            }



           /* var data = context.products.Where(x => x.pid == ID).FirstOrDefault();
            context.products.Remove(data);
            context.SaveChanges();
            return Json(1, JsonRequestBehavior.AllowGet);*/
        }
        catch (Exception ex)
        {
            return Json(0, JsonRequestBehavior.AllowGet);
        }
    }

那我怎么打这个电话呢?

好吧,你可以用很多方法。。。其中之一就是创建一个。我建议您不要从自己的MVC调用自己的webapi(这个想法是多余的…),但是,.

为什么不将ApicController调用-DocumentsController中的代码移动到一个可以从HomeController和DocumentController调用的类中呢。将其拉入从两个控制器调用的类中。你问题中的这些东西:

//查找文件的所有代码都在这里,并且工作正常

从同一网站上的另一个控制器调用API控制器是没有意义的

这也将简化代码,当您将来回到它时,您将有一个用于查找文件并在那里执行该逻辑的公共类

我想从我的HomeController调用这个方法,并将Json响应转换为List

不,你没有。您确实不想在代码触手可及时增加HTTP调用和(反)序列化的开销。它甚至在同一个集合中

你的ApiController无论如何都会与之相反。让它返回一个具体类型:

public IEnumerable<QDocumentRecord> GetAllRecords()
{
    listOfFiles = ...
    return listOfFiles;
}
同样,您不希望在控制器中使用业务逻辑,因此您将其提取到一个类中,该类为您完成工作:

public class FileListGetter
{
    public IEnumerable<QDocumentRecord> GetAllRecords()
    {
        listOfFiles = ...
        return listOfFiles;
    }
}

但是如果你真的,真的必须做HTTP请求,你可以使用
HttpWebRequest
WebClient
HttpClient
RestSharp
,所有这些都有大量的教程。

这里很晚了,但我想分享下面的代码。 如果我们将WebApi作为一个不同的项目放在同一个解决方案中,那么我们可以从MVC控制器调用它,如下所示

public class ProductsController : Controller
    {
        // GET: Products
        public async Task<ActionResult> 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<System.Data.DataTable>(data);

                }


            }
            return View();

        }
    }
公共类产品控制器:控制器
{
//获取:产品
公共异步任务索引()
{
字符串apiUrl=”http://localhost:58764/api/values";
使用(HttpClient=new HttpClient())
{
client.BaseAddress=新的Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(“应用程序/json”);
HttpResponseMessage response=await client.GetAsync(apiUrl);
if(响应。IsSuccessStatusCode)
{
var data=await response.Content.ReadAsStringAsync();
var table=Newtonsoft.Json.JsonConvert.DeserializeObject(数据);
}
}
返回视图();
}
}
控制器:

public class DocumentsController : ApiController
{
    #region Methods
    /// <summary>
    /// Get all files in the repository as Json.
    /// </summary>
    /// <returns>Json representation of QDocumentRecord.</returns>
    public HttpResponseMessage GetAllRecords()
    {
      // All code to find the files are here and is working perfectly...

         return new HttpResponseMessage()
         {
             Content = new StringContent(JsonConvert.SerializeObject(listOfFiles), Encoding.UTF8, "application/json")
         };
    }               
}
public class HomeController : Controller
{
     public Index()
     {
      // I want to call APi GetAllFiles and put the result to variable:
      var files = JsonConvert.DeserializeObject<List<QDocumentRecord>>(API return Json);
      }
 }
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var listOfFiles = new DocumentsController().GetAllRecords();
        // OR
        var listOfFiles = new FileListGetter().GetAllRecords();

        return View(listOfFiles);
    }
}
    public JsonResult GetProductsData()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:5136/api/");
            //HTTP GET
            var responseTask = client.GetAsync("product");
            responseTask.Wait();

            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<IList<product>>();
                readTask.Wait();

                var alldata = readTask.Result;

                var rsproduct = from x in alldata
                             select new[]
                             {
                             Convert.ToString(x.pid),
                             Convert.ToString(x.pname),
                             Convert.ToString(x.pprice),
                      };

                return Json(new
                {
                    aaData = rsproduct
                },
    JsonRequestBehavior.AllowGet);


            }
            else //web api sent error response 
            {
                //log response status here..

               var pro = Enumerable.Empty<product>();


                return Json(new
                {
                    aaData = pro
                },
    JsonRequestBehavior.AllowGet);


            }
        }
    }

    public JsonResult InupProduct(string id,string pname, string pprice)
    {
        try
        {

            product obj = new product
            {
                pid = Convert.ToInt32(id),
                pname = pname,
                pprice = Convert.ToDecimal(pprice)
            };



            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5136/api/product");


                if(id=="0")
                {
                    //insert........
                    //HTTP POST
                    var postTask = client.PostAsJsonAsync<product>("product", obj);
                    postTask.Wait();

                    var result = postTask.Result;

                    if (result.IsSuccessStatusCode)
                    {
                        return Json(1, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(0, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    //update........
                    //HTTP POST
                    var postTask = client.PutAsJsonAsync<product>("product", obj);
                    postTask.Wait();
                    var result = postTask.Result;
                    if (result.IsSuccessStatusCode)
                    {
                        return Json(1, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(0, JsonRequestBehavior.AllowGet);
                    }

                }




            }


            /*context.InUPProduct(Convert.ToInt32(id),pname,Convert.ToDecimal(pprice));

            return Json(1, JsonRequestBehavior.AllowGet);*/
        }
        catch (Exception ex)
        {
            return Json(0, JsonRequestBehavior.AllowGet);
        }

    }

    public JsonResult deleteRecord(int ID)
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5136/api/product");

                //HTTP DELETE
                var deleteTask = client.DeleteAsync("product/" + ID);
                deleteTask.Wait();

                var result = deleteTask.Result;
                if (result.IsSuccessStatusCode)
                {

                    return Json(1, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
            }



           /* var data = context.products.Where(x => x.pid == ID).FirstOrDefault();
            context.products.Remove(data);
            context.SaveChanges();
            return Json(1, JsonRequestBehavior.AllowGet);*/
        }
        catch (Exception ex)
        {
            return Json(0, JsonRequestBehavior.AllowGet);
        }
    }
public JsonResult GetProductsData()
{
使用(var client=new HttpClient())
{
client.BaseAddress=新Uri(“http://localhost:5136/api/");
//HTTP获取
var responseTask=client.GetAsync(“产品”);
responseTask.Wait();
var结果=响应任务结果;
if(结果。IsSuccessStatusCode)
{
var readTask=result.Content.ReadAsAsync();
readTask.Wait();
var alldata=readTask.Result;
var rsproduct=来自alldata中的x
选择新[]
{
转换为字符串(x.pid),
转换.ToString(x.pname),
转换为字符串(x.pprice),
};
返回Json(新的
{
aaData=rsproduct
},
JsonRequestBehavior.AllowGet);
}
else//web api发送了错误响应
{
//在此处记录响应状态。。
var pro=Enumerable.Empty();
返回Json(新的
{
aaData=pro
},
JsonRequestBehavior.AllowGet);
}
}
}
public JsonResult InupProduct(字符串id、字符串pname、字符串pprice)
{
尝试
{
产品obj=新产品
{
pid=转换为32(id),
pname=pname,
pprice=转换为特定值(pprice)
};
使用(var client=new HttpClient())
{
client.BaseAddress=新Uri(“http://localhost:5136/api/product");
如果(id=“0”)
{
//插入。。。。。。。。
//HTTP POST
var postTask=client.postsjsonasync(“产品”,obj);
postTask.Wait();
var result=postTask.result;
if(结果。IsSuccessStatusCode)
{
返回Json(1,JsonRequestBehavior.AllowGet);
}
其他的
{
返回Json(0,JsonRequestBehavior.AllowGet);
}
}
其他的
{
//更新。。。。。。。。
//HTTP POST
var postTask=client.PutAsJsonAsync(“产品”,obj);
postTask.Wait();
var result=postTask.result;
if(结果。IsSuccessStatusCode)
{
返回Json(1,JsonRequestBehavior.AllowGet);
}
其他的
{