如何使用参数调用WebApi方法

时间:2015-08-11 19:45:24

标签: asp.net asp.net-mvc-4 asp.net-web-api2

我有一个带有2个参数的WebApi方法:

public IQueryable<Facilities> GetFacilityList(string baseCode, string scope)
{
    return Object;
}

在我的Asp.Net MVC中,到目前为止我有以下内容:

    public ActionResult FacilityGrid()
    {
        List<Facilities> query;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:8080/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));




            HttpResponseMessage response = await client.GetAsync("api/facilities");
            if (response.IsSuccessStatusCode)
            {
             //   Product product = await response.Content.ReadAsAsync>Product>()
            }

        }

}

如何调用WebApi并传入两个参数?

1 个答案:

答案 0 :(得分:0)

您可以按照代码发布中的建议手动创建查询字符串,也可以使用类似UriBuilder的类。这种方法似乎产生了预期的反应。

 public async Task<ActionResult> QuetionTwoApiCall()
    {
         var builder = new UriBuilder("http://localhost/api/question2");
         builder.Port = 50742;
         var query = HttpUtility.ParseQueryString(builder.Query);
         query["basecode"] = "somebasecode";
         query["scope"] = "somescope";
         builder.Query = query.ToString();       
         string url = builder.ToString();
         using (var client = new HttpClient()) {

             client.DefaultRequestHeaders.Accept.Clear();
             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
             HttpResponseMessage  response = await client.GetAsync(new Uri(url));
             string donothing = "do nothing";
       }
         return RedirectToAction("QuestionTwo");
    }
}