【问题标题】:How to pass JSON string from ASP.Net to WebAPI Get Method?如何将 JSON 字符串从 ASP.Net 传递到 WebAPI 获取方法?
【发布时间】:2015-04-23 11:02:05
【问题描述】:

我有一个如下所示的 WebAPI Get 方法

// GET api/Employee/5
public tblEmployee GettblEmployee(int id)
{
    tblEmployee tblemployee = db.tblEmployees.Find(id);
    if (tblemployee == null)
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
    }

     return tblemployee;
 }

我正在尝试从 ASP.NET 互联网应用程序调用它

HttpClient hc;
hc = new HttpClient();
string uriStr = "http://localhost/api/Employee/";

HttpResponseMessage response = hc.GetAsync(uriStr + "2").Result;

var obj = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);

ViewBag.Message = obj.ToString();
return View();

现在我想将 JSON 从 ASP 网站传递到 WebAPI,有人可以帮助我吗?我用谷歌搜索了很多,但我只能找到来自 JQuery 的调用

【问题讨论】:

    标签: c# asp.net json asp.net-mvc asp.net-web-api


    【解决方案1】:

    您可以使用PostAsJsonAsync

    using (HttpClient hc = new HttpClient())
                {
                    var myModel = new Model()
                    {
                    prop1 = "prop1", prop2 = 1, prop3 = "prop3"
                    };
                    HttpResponseMessage response = await client.PostAsJsonAsync("api/Employee/", myModel);
                    if (response.IsSuccessStatusCode)
                    {
    
                    }
                }
    

    Example

    【讨论】:

    • 嗨,Shah,我想基本上将 JSON 从 ASP.Net 传递到 WebAPI。我的 WebAPI 将返回一个 JSON,我需要从 ASP.Net 接收它。你能帮我解决这两种方法吗?它是 WebAPI 中的某种自定义 POST/GET 方法吗?
    • 所以你可以使用上面的代码,PostAsJsonAsync 用于发布 json 数据,告诉我一件事,这个 api/Employee/ 接受什么作为参数?是模态还是字符串 json?
    • 现在它只是一个字符串,我希望它接受一个 JSON 并返回一个 JSON,所以该方法字符串 strOutput = 'some json string' HttpResponseMessage response = Request.CreateResponse (HttpStatusCode.Created, strOutput);返回响应;
    猜你喜欢
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2012-11-22
    相关资源
    最近更新 更多