【问题标题】:How do I call WebApi method with parameters如何使用参数调用 WebApi 方法
【发布时间】:2015-08-11 19:45:23
【问题描述】:

我有一个带有 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并传入两个参数?

【问题讨论】:

  • 将它们添加到查询字符串中?
  • 尝试使用 api/facilities?baseCode=baseCodeInput&scope=scopeInput

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


【解决方案1】:

您可以按照代码帖子评论中的建议手动创建查询字符串,也可以使用 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");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 2016-08-05
    相关资源
    最近更新 更多