如何将ASP.Net中的JSON字符串传递给WebAPI Get方法?

时间:2015-04-23 11:02:05

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

我有一个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,有人可以帮助我。我用Google搜索了很多但我只能从JQuery调用

1 个答案:

答案 0 :(得分:0)

您可以使用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