簡體   English   中英

使用C#中的對象將JSON數據發布到Web API

[英]Post JSON data to web API using object in C#

我能夠編寫代碼以從Web API執行GET操作。 但是,我無法發布。 我認為問題出在JSON對象上。 如果參數是通過URL發送的,則可以發布消息,但是如果它是JSON對象,則無法發送消息。 例如:POST要求我通過URL和ReferenceString作為JSON對象發送ModelID,CustomerID。

數據發布

型號ID = 3345

客戶編號= 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 
    }

您能糾正我哪里出錯了嗎?

多虧梅森! 我編寫了使用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;

    }

POST函數將如下所示。

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

創建一個DTO類作為參考ID

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);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM