WebApi程序可在方法参数前加[FromBody]标识,表示该参数值应该从请求的Body中获取,而不是从URL中获取。
从URL获取参数值的方式的弊端是URL有长度限制,当超过浏览器的最大URL长度时请求将被浏览器拒绝,根本不会发出去。
因此,当参数值过大时需要用[FromBody]参数进行传输。
以下是WebApi接口定义,很简单,只为说明用法:
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
protected HttpResponseMessage GetJsonResponse(string json)
{
HttpResponseMessage result;
result = new HttpResponseMessage { Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json") };
//result.Headers.Add("Access-Control-Allow-Origin", "*"); //设置HTTP头允许 返回的跨域信息给浏览器解析
return result;
}
需要注意的是: [FromBody] 参数不能是基本的数据类型(如byte、int、bool、DateTime、string等)。
以下是C#客户端请求的代码
/// <summary>
/// 通过请求体向指定URL传输数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="objBody">需传输的数据</param>
/// <returns></returns>
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
function Send(url, objBody) {
$.ajax({
url: url,
type: "post",
data: JSON.stringify(objBody),
contentType: "application/json; charset=UTF-8",
timeout: 5000,
success: function (result) {
alert("data = " + JSON.stringify(result));
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
};