asp.net - 如何使用 HttpClient 将 Json 数据作为参数传递给 web api

标签 asp.net json asp.net-web-api

我正在使用一个 asp.net 应用程序,我在其中使用 HttpClient 调用 web api。

在 Web API Controller 中,我传递了两个参数,一个是 int,第二个是 string。

代码如下:

public HttpResponseMessage Get(int submissionID, string jsonData)
{

}

当我使用 httpClient 传递一个 int 和一个字符串参数时,这工作正常没有问题

下面是我的httpClient代码:

public void GetWebApiData(int fileID, String jsonData)
{
    var client = new HttpClient();
    var task = client.GetAsync("http://localhost:1469/api/Smartling/" + fileID + "/"+jsonData)
      .ContinueWith((taskwithresponse) =>
      {
          var response = taskwithresponse.Result;
          var jsonString = response.Content.ReadAsStringAsync();
          jsonString.Wait();
          var getVal = jsonString.Result;

      });
    task.Wait();
} 

在上面的代码中,如果我传递的不是 json 数据,它会给出错误响应代码 400 Bad Request。

同样,我使用了 jQuery ajax 调用,它工作正常,没有问题。

如何将JSON数据作为参数传递?

最佳答案

假设你有课

public class Sample
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
}

在客户端

public async static Task<Boolean> GetWebApiData(int fileID,string jsonData)
{
    var client = new HttpClient();
    Sample model = new Sample();
    model = Newtonsoft.Json.JsonConvert.DeserializeObject<Sample>(jsonData);
    var response = await client.GetAsync(string.Format("http://sample.com/api/test/{0}?model.value1={1}&model.value2={2}", fileID ,model.Value1, model.Value2));
    if (response.StatusCode == HttpStatusCode.OK)
        return true;
    else
        return false;
}

在服务器端

[HttpGet]
public IHttpActionResult Get(int id,[FromUri]Sample model)
{
    //do something
    return Ok();
}

关于asp.net - 如何使用 HttpClient 将 Json 数据作为参数传递给 web api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37721300/

相关文章:

c# - .NET Google Calendar API 按日期排序事件

javascript - JSON 对象根据位置返回值

java - 如何使用 GSON 比较两个 JSON 字符串是否相等?

c# - 返回 Azure TableEntity 对象列表时出现 SerializationException

asp.net-mvc - 如何从 ASP.NET MVC Web API 帖子中获取原始 JSON 字典?

c# - 动态创建的链接按钮上的单击事件不起作用

html - 覆盖 Bootstrap 默认字体(最佳实践)

c# - 更新到 beta8 后无法发布 asp.net 5 应用程序 - 依赖项......无法解决

javascript - 抓取 html 页面并将其转换为 json 对象

c# - 在服务器端同时进行排序和分页的 DocumentDb 查询,可能吗?