繁体   English   中英

带有身份验证问题的 C# HTTP Post

[英]C# HTTP Post with Authentication issue

我正在尝试学习如何使用 REST API。 不幸的是,我正在使用的那个需要身份验证,我无法正确获取代码。 有人愿意帮我弄明白我的代码吗?

 using System;
    using System.Text;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    using System.Collections.Generic;

    namespace HttpClientAuth
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var userName = "admin";
                var passwd = "adminpw";
                var url = "http://10.10.102.109/api/v1/routing/windows/Window1";

                using var client = new HttpClient();

                var authToken = Encoding.ASCII.GetBytes($"{userName}:{passwd}");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                        Convert.ToBase64String(authToken));

                var result = await client.GetAsync(url);

                var requestContent = new HttpRequestMessage(HttpMethod.Post, url);

                //Request Body in Key Value Pair
                requestContent.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    ["CanYCentre"] = "540",
                    ["CanXCentre"] = "960",
                });

                var content = await result.Content.ReadAsStringAsync();
                Console.WriteLine(content);
            }
        }
    }

似乎您对如何发出POST请求感到困惑。 您可以尝试以下代码段。

         ApiRequestModel _requestModel = new ApiRequestModel();

        _requestModel.RequestParam1 = "YourValue";
        _requestModel.RequestParam2= "YourValue";


        var jsonContent = JsonConvert.SerializeObject(_requestModel);
        var authKey = "c4b3d4a2-ba24-46f5-9ad7-ccb4e7980da6";
        var requestURI = "http://10.10.102.109/api/v1/routing/windows/Window1";
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(requestURI);
            request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
            request.Headers.Add("Authorization", "Basic" + authKey);

            var response = await client.SendAsync(request);


            //Check status code and retrive response

            if (response.IsSuccessStatusCode)
            {

                dynamic objResponse = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
            }
            else
            {
                dynamic result_string = await response.Content.ReadAsStringAsync();
            }

        }

更新:根据您给出的评论截图,您也可以尝试这种方式。

private async Task<string> HttpRequest()
    {
        //Your Request End Point
        string requestUrl = $"http://10.10.102.109/api/v1/routing/windows/Window1";
        var requestContent = new HttpRequestMessage(HttpMethod.Post, requestUrl);

        //Request Body in Key Value Pair
        requestContent.Content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["CanYCentre"] = "540",
            ["CanXCentre"] = "960",
        });

        requestContent.Headers.Add("Authorization", "Basic" + "YourAuthKey");

        HttpClient client = new HttpClient();
        //Sending request to endpoint
        var tokenResponse = await client.SendAsync(requestContent);
        //Receiving Response
        dynamic json = await tokenResponse.Content.ReadAsStringAsync();
        dynamic response = JsonConvert.DeserializeObject<dynamic>(json);

        return response;
    }

更新 2:

If you still don't understand or don't know how you would implement it Just copy and paste below code snippet.


  private static async Task<string> HttpRequest()
        {

            object[] body = new object[] 
            {
                new { CanYCentre = "540" },
                new { CanYCentre = "960" }
            };
            var requestBody = JsonConvert.SerializeObject(body);

            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                request.Method = HttpMethod.Post;
                request.RequestUri = new Uri("http://10.10.102.109/api/v1/routing/windows/Window1");
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                request.Headers.Add("Authorization", "Basic" + "YourAuthKey");

                var response = await client.SendAsync(request);
                var responseBody = await response.Content.ReadAsStringAsync();

                dynamic result = JsonConvert.DeserializeObject<dynamic>(responseBody);
                return result;
            }

        }

希望这会帮助你。 如果您遇到任何问题,请随时分享。

对于那些正在寻找带有身份验证的 C# Http JSON PUT 的替代版本的人:

using System;
using System.Text;
using System.Net;
using System.IO;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            //URL
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");

            //Basic Authentication
            string authInfo = "admin" + ":" + "adminpw";
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            httpWebRequest.Headers["Authorization"] = "Basic " + authInfo;

            //Application Type
            httpWebRequest.ContentType = "application/json";

            //Method
            httpWebRequest.Method = "PUT";

            // JSON Body
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"ID\":\"1\"," +
                              "\"Phone\":\"1234567890\"}";

                streamWriter.Write(json);
                Console.WriteLine("PUT Body: " + json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }

            //Status Code
            Console.WriteLine("URL: " + httpWebRequest.RequestUri);
            Console.WriteLine("Status Discription " + httpResponse.StatusDescription);

            if (httpResponse.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine("Status code " +(int)httpResponse.StatusCode + " " + httpResponse.StatusCode);
            }
            else 
            {
                Console.WriteLine("Status code " + (int)httpResponse.StatusCode + " " + httpResponse.StatusCode);
            }
            // Close the response.
            httpResponse.Close();
        }
    }
}

暂无
暂无

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

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