.net MVC APi调用

常用的调用方法为Get/Post

Get方法:

服务器

public string Get(int id)
{
    return "value";
}

这个直接在网页就可以测试,用 http://地址/api/xxx(Controller名,即xxxController的xxx部分)?id=x即可看到返回值

调用参数名即为方法的参数名

Post方法:

服务器

public string Post([FromBody]test t)
{
    return t.aa;
}

客户端

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(WebCall.serverurl);
    test t = new test();
    t.aa = "a";
    t.bb = "b";
    var requestJson = AppUtils.JsonSerializer<test>(t);
    HttpContent httpContent = new StringContent(requestJson);
    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    var result = client.PostAsync("Values", httpContent).Result.Content.ReadAsStringAsync().Result;
    MessageBox.Show(result);
}

其中,服务器与客户端的tt类为有aa,bb两个属性的类。在客户端调用时,参数对象名要与服务器参数名一致,如上例中的t

原文地址:https://www.cnblogs.com/punkrocker/p/4537312.html