使用C#中的对象将JSON数据发布到Web API

时间:2017-06-26 14:49:47

标签: c# .net json web-services http

我能够编写代码以从Web API执行GET操作。但是,我无法发帖。我认为问题在于JSON对象。如果参数是通过URL发送的,我可以POST,但如果它是JSON对象,我就无法这样做。例如:POST要求我通过URL和ReferenceString作为JSON对象发送ModelID,CustomerID。

要发布的数据

  

ModelID = 3345

     

CustomerID = 1V34858493

     

ReferenceID是一个JSON字符串[]

     

[     {       “ReferenceId”:“a123”     }   ]

主要

 static void Main(string[] args) 
    {
       // JavaScriptSerializer serializer = new JavaScriptSerializer();

        string patientServiceResponse = PostRequest( string.Format("https://url.com/api/{0}/{1}/taskOrders", 3345, "1V34858493"));

        Debug.Write(patientServiceResponse);
    }

POST请求

private static string PostRequest(string url)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";
        httpWebRequest.Accept = "application/json; charset=utf-8";
        string sContentType = "application/json";

        JObject oJsonObject = new JObject();

        oJsonObject.Add("ReferenceId", "a123");

        HttpClient oHttpClient = new HttpClient();
        var oTaskPostAsync = oHttpClient.PostAsync(url, new StringContent(oJsonObject.ToString(), Encoding.UTF8, sContentType));

        //return 
    }

如果我出错了,请你纠正我。

2 个答案:

答案 0 :(得分:2)

感谢梅森!我编写了代码,使用HttpWebRequest将数据发布到Web API。

主要

static void Main(string[] args) 
{
    string patientServiceResponse = PostRequest( string.Format("https://url.com/api/{0}/{1}/taskOrders", 3345, "1V34858493"));

    Debug.Write(patientServiceResponse);
}

发表

private static string PostRequest(string url)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "[  { \"ReferenceId\": \"a123\"  } ]";
            Debug.Write(json);
            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }
        try
        {
            using (var response = httpWebRequest.GetResponse() as HttpWebResponse)
            {
                if (httpWebRequest.HaveResponse && response != null)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        result = reader.ReadToEnd();
                    }
                }
            }
        }
        catch (WebException e)
        {
            if (e.Response != null)
            {
                using (var errorResponse = (HttpWebResponse)e.Response)
                {
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        string error = reader.ReadToEnd();
                        result = error;
                    }
                }

            }
        }

        return result;

    }

答案 1 :(得分:0)

POST功能将如下所示。

    [HttpPost]
    [Route("{modelId}/{customerId}")]
    public IHttpActionResult Add(string modelId, string customerId, REFDto referenceId)
    {
        return Ok();
    }

为参考ID

创建DTO类
public class REFDto
{
    public string referenceId { get; set; }
}

API客户电话:

        using (var client = new HttpClient())
        {
            var modelId = "3345";
            var customerId = "1V34858493";
            var url = $"https://url.com/api/{modelId}/{customerId}/taskOrders";
            JObject oJsonObject = new JObject();
            oJsonObject.Add("referenceId", "ref123");
            var response = await client.PostAsync(url, new StringContent(oJsonObject.ToString(), Encoding.UTF8, "application/json"));
            Console.WriteLine(response);
        }