1

我对 mvc web api 很陌生

我已经创建了一个 web api Post 方法,它采用对象类型“Bag”并返回一个 HTMLString,代码如下所示

public HtmlString PostBag(Bag bagofItem)
    {
       return  Utility.PostBagDiscountedItem(bagofItem);
    }

现在从我的网站我想从控制器 PostBag() 调用 API 方法 PostBag

如果有人能告诉我如何做到这一点,我不知道该怎么做

我在我的网络应用程序中得到的如下所示。

public class HomeController : Controller
{
    private Bag _bag = new Bag();
    private string uri = "http://localhost:54460/";

 public ActionResult PostBag()
    {
          // would some one show me how to POST the _bag to API Method PostBag()

        return View();
    }

public class Bag 
{
    private static  List<Product> _bag { get; set; }

    public List<Product> GetBag ()
    {
        if (_bag == null)
            _bag = new List<Product>();
       return _bag;
    }
}
4

1 回答 1

0

尝试这个:

using (var client = new HttpClient())
{

   client.BaseAddress = new Uri("http://localhost:54460/");

   client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

   HttpResponseMessage response = await client.GetAsync(_bag);

   if (response.IsSuccessStatusCode)
   {
       Console.WriteLine("Success");
   }
   else
   {
       Console.WriteLine("Error with feed");
   }
}
于 2016-11-01T22:33:58.263 回答