简体   繁体   English

C#中的HttpWebRequest POST

[英]HttpWebRequest POST in c#

I have an Api that allows users to be inserted into the database. 我有一个允许用户插入数据库的Api。 I am trying requesting the Api in a windows forms application but keep getting System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'I am relatively new to Api requests. 我正在尝试在Windows窗体应用程序中请求Api,但始终收到System.Net.WebException:'远程服务器返回了错误:(403)禁止。'我对Api请求而言相对较新。 Can anyone see what I am doing incorrectly, thanks. 谁能看到我做错的事情,谢谢。

Customer class: 客户类别:

public class Customer
    {
        public int StoreCustomerID { get; set; }
        // Actaul customer from store ID
        public string Number { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string Country { get; set; }
        public string MobilePhone { get; set; }
        public System.DateTime DOB { get; set; }
        public string Phone { get; set; }
        //public User Credentials { get; set; }
        public string DeviceToken { get; set; }
        //public CustomerCard Details { get; set; }
        public string Gender { get; set; }
        public bool IsError { get; set; }
        public string ErrorMessage { get; set; }
        //Public Property StoreNumber As Integer


            public string Token { get; set; }
            public bool Authenticated { get; set; }
            public string SecretKey { get; set; }

    }

ApiRequest class: ApiRequest类:

private void button1_Click(object sender, EventArgs e)
        {

            Customer cust = new Customer();
            InsertUpdateCustomer(cust, "http://Example.com");
        }

        public static Customer InsertUpdateCustomer(Customer MyCustomer, string ServerAddress)
        {

            //Dim PostData As New CardInfo With {.CardNumber = CardNumber, .Reference = Reference, .SaleDate = DateTime.Now, .SaleTotalAmount = Amount, .StoreNumber = StoreNumber, .TransactionTypeID = Transaction}

            //Customer Res = new Customer();
            string webAddr = ServerAddress + "/api/Customer/Insert";


            WebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers.Add("X-Giftworx-App", "Posworx");
            httpWebRequest.Timeout = 4000;

            MyCustomer.Name = "Janice";
            MyCustomer.Surname = "Alexander";
            MyCustomer.Email = "j@example.com";
            MyCustomer.MobilePhone = "0314011828";
            MyCustomer.Gender = "Female";
            MyCustomer.DOB = DateTime.Now;
            MyCustomer.Token = "wMq0cZ4iN7uOnJdrSdYITQcWHQ9VYgiLCosN7Rj9MSdqmZKSTuHCb08jeO/wlp3bCoK/sbEwwvjlZUeQdj8p5w==";
            MyCustomer.SecretKey = "jdghe45";
            MyCustomer.Authenticated = true;


            try
            {
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {

                    string jsonstring;


                    MemoryStream stream1 = new MemoryStream();

                    //Serialize the Record object to a memory stream using DataContractJsonSerializer.
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Customer));
                    ser.WriteObject(stream1, MyCustomer);


                    stream1.Position = 0;

                    StreamReader sr = new StreamReader(stream1);

                    jsonstring = sr.ReadToEnd();

                    Debug.WriteLine("JSON form of Insert Loyaltyworx Update Customer object: ");
                    Debug.WriteLine(JObject.Parse(jsonstring));

                    streamWriter.Write(jsonstring);
                    streamWriter.Flush();
                }
            }
            catch (Exception ex)
            {
                return null;
            }

            try
            {
                HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        string result = streamReader.ReadToEnd();
                        Console.WriteLine(JObject.Parse(result));

                        Customer MyResult = JsonConvert.DeserializeObject<Customer>(result);


                        Debug.WriteLine(JObject.Parse(result));

                        return MyResult;

                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {

                return null;
            }

        }

You can convert your data in to a json string as below 您可以将数据转换为json字符串,如下所示

 Customer cust = new Customer();
 var json = new JavaScriptSerializer().Serialize(cust );
 JObject json2 = JObject.Parse(json);

and then you can make a call like this. 然后您可以拨打这样的电话。

 string webAddr = ServerAddress + "/api/Customer/Insert";
 HttpClient client = new HttpClient();
 HttpResponseMessage response = client.PostAsJsonAsync(webAddr , json2).Result;

确保您正在以管理员身份使用应用程序,并检查防火墙/防病毒程序没有被阻止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM