命名空间
System.Net.Http
Post请求
1.如果参数是 ?phone="15071651111" 的形式发起的post请求 则webapi中 Controller 的方法需要加上 [FromQuery]
例:
string url = _userServiceUrl + "api/User/CheckOrCreate?phone=" + phone;
var response = await _httpClient.PostAsync(url, null);
webapi:
public async Task<IActionResult> CheckOrCreate([FromQuery]string phone)
{
//dosomething...
}
2.如果参数是通过HttpContent发送的单个字符串则webapi中 Controller 的方法需要加上 [FromForm]
例:
var data = new FormUrlEncodedContent(new Dictionary<string, string> {{"phone",phone }});
var response = await _httpClient.PostAsync(url, data);
webapi:
public async Task<IActionResult> CheckOrCreate([FromForm]string phone)
{
//dosomething...
}
3.如果参数是通过HttpContent发送的JSON则webapi中 Controller 的方法需要加上 [FromBody]
例:
string url = _userServiceUrl + "api/User/CheckOrCreate";
UserInfoDto dto = new UserInfoDto { Name = "Yuan", Phone = phone };
var data = new StringContent(JsonConvert.SerializeObject(dto),Encoding.UTF8,"application/json");
webapi:
public async Task<IActionResult> CheckOrCreate([FromBody]CheckOrCreateAppUserViewModel model)
{
//dosomething
}
注意
控制器内不要声明多个同名不同参且请求方式也一样的控制器,否则会提示匹配多个路由的问题(也有可能是我路由没有配好的原因)