[C#][WebAPI]返回 json

时间:2022-03-23 00:21:05
//将webapi的返回值设为Json格式
var jsonFormatter = new JsonMediaTypeFormatter();
GlobalConfiguration.Configuration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); // ---- 或者这样:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

客户端调用的方式为:

var web = "http://weburl/api";
var request = WebRequest.Create(web);
request.ContentType = "application/json";
request.Method = "Post"; string json = JsonConvert.SerializeObject(new
{
Arg1 = "arg1"
});
using (var sw = new StreamWriter(request.GetRequestStream()))
{
sw.Write(json);
}
var response = request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
var str = sr.ReadToEnd();
try
{
var obj = JsonConvert.DeserializeObject<object>(str);
if (obj != null)
{
if (obj.errorCode == )
{
return obj.data;
}
else
{
msg = obj.message;
}
}
}
catch (Exception ex)
{
msg = string.Format("错误:{0}", ex.Message);
}
}
return msg;