【问题标题】:web api call from code behind来自后面代码的 web api 调用
【发布时间】:2013-07-25 10:35:03
【问题描述】:

我对 mvc web api 很陌生

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

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

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

如果有人可以告诉我如何做到这一点,我不知道该怎么做并且感激不尽

我的 Web 应用程序如下所示。

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;
    }
}

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api


    【解决方案1】:

    试试这个:

    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");
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多