我正在尝试通过HTTP POst请求发送动态对象,但是当我收到该对象时,它为null。
我无法使用JObject,因为我有一个“虚拟” api,并且它不接受JObjects。
我尝试发送类型对象和动态对象。他们两个都不起作用。可以帮助我吗?
这是我的发帖请求:
public static void Post(string uri, object parameter, string serviceName)
{
StringBuilder url = new StringBuilder();
url.Append(uri);
var client = GetClient(url.ToString(), 300, "application/json");
var urlParameters = GetUrlParameters(new List<KeyValuePair<string, object>>() { });
var response = client.PostAsync(
urlParameters,
new StringContent(
JsonConvert.SerializeObject(parameter).ToString(),
Encoding.UTF8,
"application/json")
).Result;
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception($"{serviceName}: {response.StatusCode}");
}
[这里是我收到该帖子的位置:
方法的干预:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "Teste")]
void Teste(object requestData);
在类中实现的方法(这是我获取数据的地方):
public void Teste(object requestData)
{
var teste = requestData;
var t1 = JsonConvert.SerializeObject(requestData); // this returns {}; (empty)
}
您可以稍微调整一下POST来解决其他问题吗?类似于以下内容? (未编译)
var rawJson = await client.PostAsync(
urlParameters,
new StringContent(
JsonConvert.SerializeObject(parameter).ToString(),
Encoding.UTF8,
"application/json")
).Content.ReadAsStringAsync();
var mappedObj = JsonConvert.DeserializeObject<T>(rawJson,
new JsonSerializerSettings
{
Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
// convert this to your logger
LogHelper.Instance.Warning(2000, string.Format("Failed object mapping: {0}\n{1}",
args.ErrorContext.Error, rawJson));
args.ErrorContext.Handled = true;
},
// set culture to mitigate mapping issues related to dates/numbers
// https://stackoverflow.com/a/34529198
Culture = CultureInfo.InvariantCulture
});