任务是在json中序列化类并将其传递给服务器上的POST。我写了代码并且它有效,但我感觉我做了很多不必要的事情。及时的良好实践来解决我的问题。
//package - a serializable object that must be passed
JsonPackage package = new JsonPackage( userData );
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer( typeof( JsonPackage ) );
WebRequest request = WebRequest.Create( "http://localhost:52733/set" );
request.ContentType = "application/json";
request.Method = "POST";
MemoryStream ms = new MemoryStream();
jsonFormatter.WriteObject( ms, package );
ms.Flush();
ms.Position = 0;
StreamReader sr = new StreamReader( ms );
string jsonString = sr.ReadToEnd();
StreamWriter sw = new StreamWriter( request.GetRequestStream() );
sw.Write( jsonString );
sr.Dispose();
sw.Dispose();
ms.Dispose();
request.GetResponse();
更新 感谢所有的答案,你帮助我学到了很多东西。我接受了另一个建议并写了如下:
//package - a serializable object that must be passed
JsonPackage package = new JsonPackage( Data );
DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer( typeof( JsonPackage ) );
WebRequest request = WebRequest.Create( "http://localhost:52733/set" );
request.ContentType = "application/json";
request.Method = "POST";
using ( var stream = request.GetRequestStream() )
{
jsonFormatter.WriteObject( stream, package );
}
request.GetResponse();
告诉我我的决定存在缺陷吗?
答案 0 :(得分:1)
如果您使用NewtonSoft.Json
,序列化步骤将是一个简单的JsonConvert.SerializeObject(<<object>>)
。希望这会有所帮助。\
以下是您的代码的简化版本。
var client = new System.Net.Http.HttpClient();
var content = new StringContent(JsonConvert.SerializeObject(data));
client.BaseAddress = new Uri("http://localhost:52733/");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsync("set", content).Result;
//do what ever you want to do with response
答案 1 :(得分:1)
您确实可以使用HttpClient
及其PostAsJsonAsync
方法减少行数。由于该方法是异步的,并且我假设您的代码可能不是的方法,您将需要访问PostAsJsonAsync
的awaiter来获取请求的结果。
var client = new HttpClient();
// response is an HttpResponseMessage instance
var response = client.PostAsJsonAsync("http://localhost:52733/set", userData)
.GetAwaiter().GetResult();
您还可以在那里获得有关HttpClient
用法的更多详细信息:https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
答案 2 :(得分:0)
我希望我能提供帮助。我用restSharp。 要使用它,您需要安装RestSharp
http://restsharp.org/ https://www.nuget.org/packages/RestSharp/106.3.0-alpha0002
和NewtonSoft.Json。
private bool Post(<<DataStaructure>> inputParam)
{
var jsonSerializerSettings =
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var client = new RestClient("http://localhost:52733/set/");
var request = new RestRequest(Method.POST);
var jsonToSend = JsonConvert.SerializeObject(inputParam, jsonSerializerSettings);
request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
if (response.IsSuccessful == false)
{
throw new Exception(response.ErrorMessage);
}
else
{
return Convert.ToBoolean(response.Content);
}
}