как разместить данные формы с помощью HttpClient в webapi в asp. net ядре - PullRequest
1 голос
/ 06 апреля 2020

ScreenShot

Я получаю эту ошибку в c# коде StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'. но в почтальоне я получаю код состояния 200 OK.

    public static void RunPostAsync(FindStaffModel inputs, string token)
    {
        HttpClient client = new HttpClient();
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.BaseAddress = new Uri("https://api..................Enquiry");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        string json = JsonConvert.SerializeObject(inputs, Formatting.Indented);

        var buffer = System.Text.Encoding.UTF8.GetBytes(json);

        var byteContent = new ByteArrayContent(buffer);

        var httpResponce = new HttpResponseMessage();
        try
        {
            httpResponce = client.PostAsync("https://api..................Enquiry", byteContent).Result;
            using (HttpContent contents = httpResponce.Content)
            {
                var result = contents.ReadAsByteArrayAsync().Result;
                var res = (System.Text.Encoding.UTF8.GetString(result));
                Console.WriteLine("result :" + res);

            }
        }
        catch (Exception ex)
        {

            Console.WriteLine("error" + ex);
            //Console.WriteLine("respose" + httpResponce);
        }
    }

я также пробую этот код, но я получаю ту же ошибку StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1 , Содержимое: System. Net .Http.HttpConnectionResponseContent, Заголовки: {Cache-Control: no-cache Pragma: no-cache Сервер: Microsoft-IIS / 10.0 X-As pNet -Версия: 4.0.30319 X-Powered -By: ASP.NET Дата: Пн, 06 Апр. 2020 16:42:33 GMT Истекает: -1 Длина контента: 0}}

public static void RunPostAsync(FindStaffModel inputs, string token)
        {

            using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
            {
                using (var client = new HttpClient(handler) { BaseAddress = new Uri("https://api..................Enquiry") })
                {
                    //add parameters on request
                    var body = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("FirstName", "test"),
                        new KeyValuePair<string, string>("LastName", "test"),
                        new KeyValuePair<string, string>("JobTitleId", "1"),
                        new KeyValuePair<string, string>("JobTitle", ".Net Developer"),
                        new KeyValuePair<string, string>("JobTypeId", "2"),
                        new KeyValuePair<string, string>("JobType", "Part Time") . . . . . . . .


                    };

                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://api...............Enquiry");

                    //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
                    client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
                    client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
                    client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                    client.Timeout = TimeSpan.FromMilliseconds(10000);

                    var res = client.PostAsync("https://api.........Enquiry", new FormUrlEncodedContent(body)).Result;

                }
            }
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...