简体   繁体   English

C# HttpClient REST 请求使用 Content-Type: application/x-www-form-urlencoded

[英]C# HttpClient REST request using Content-Type: application/x-www-form-urlencoded

I'm trying to debug this request, but I don't see what I'm doing wrong.我正在尝试调试此请求,但我看不出我做错了什么。 The request is for auth info, and it's pretty simple.该请求是针对身份验证信息的,非常简单。

curl -i -X POST \
   -H "Content-Type:application/x-www-form-urlencoded" \
   -d \
'user_name=ecommemail&password=abc123&auth_type=password' \
 'https://sample.com/api/auth/token'

Here is my latest effort.这是我最近的努力。

authUrl = https://sample.com/api/auth/token;

private async Task<string> GenerateAccessObject2()
{
    HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };
    HttpClient client = new HttpClient(handler);
    client.BaseAddress = new(authUrl);
    //client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));            

    List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();
    postData.Add(new KeyValuePair<string, string>("username", "email"));
    postData.Add(new KeyValuePair<string, string>("password", "abc123"));
    postData.Add(new KeyValuePair<string, string>("auth_type", "password"));

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, authUrl) { Content = new FormUrlEncodedContent(postData) };
    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

    System.Console.WriteLine(request.ToString());
    System.Console.WriteLine(request.Content);
    HttpResponseMessage response = await client.SendAsync(request);

    return response.ToString();
}

I can see in the debugger that the Content-Type header is set (client.Content.Headers).我可以在调试器中看到 Content-Type header 已设置(client.Content.Headers)。 And the Accept is set too (client.Headers).并且 Accept 也设置了(client.Headers)。

I'm not sure I'm setting the body content correctly though.我不确定我是否正确设置了正文内容。 I have 62 characters worth.我有 62 个字符。 In the request it says I have 63 set, but I can't figure out how to actually see or print the body content in the request...在请求中它说我有 63 组,但我无法弄清楚如何在请求中实际查看或打印正文内容......

The print statement gives this:打印语句给出了这个:

Method: POST, RequestUri: 'https://sample.com/api/auth/token', Version: 1.1, Content: System.Net.Http.FormUrlEncodedContent, Headers:
{
  Content-Type: application/x-www-form-urlencoded
}

And here is the error:这是错误:

StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Max-Forwards: 20
  Via: 1.0 sample.com ()
  Connection: close
  X-CorrelationID: Id-d26af9610df7cc527996cde2 0
  Date: Tue, 01 Feb 2022 17:16:02 GMT
  Server: Apache
  Transfer-Encoding: chunked
  Content-Type: application/json
}

[EDIT] Another effort using MihalBy's idea. [编辑] 使用 MihalBy 的想法的另一项努力。

private async Task<string> GenerateAccessObject3()
{
    HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };
    HttpClient client = new HttpClient(handler);
    client.BaseAddress = new(authUrl);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    string postData = HttpUtility.UrlEncode(authBody, Encoding.GetEncoding(65001));
    byte[] data = System.Text.Encoding.GetEncoding(65001).GetBytes(postData);
    ByteArrayContent content = new ByteArrayContent(data);
    content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

    HttpResponseMessage response = await client.PostAsync(authUrl, content);

    return response.ToString();
}

This escapes the form body into something like this: "user_name%3decommemail%26password%3abc123m%26auth_type%3dpassword"这会将表单主体转义为如下内容:“user_name%3decommemail%26password%3abc123m%26auth_type%3dpassword”

And I get a 400 Bad Request error, which I consider progress.我收到一个 400 Bad Request 错误,我认为这是一个进步。

try to post using FormUrlEncodedContent尝试使用 FormUrlEncodedContent 发布

HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false };
    HttpClient client = new HttpClient(handler);
    client.BaseAddress = new(authUrl);
  client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));            

var data=new Dictionary<string, string>()
    {
            {"username", "email"},
             {"password", "abc123"}
             { "auth_type", "password"}
    };

var content = new FormUrlEncodedContent(data);

var response = await client.PostAsync(authUrl, content);

if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);

}

暂无
暂无

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

相关问题 如何在内容类型为x-www-form-urlencoded的C#中发布请求? - How to POST request in c# with content-type being x-www-form-urlencoded? 使用HttpClient的C#application / x-www-form-urlencoded OAuth和HTTP REST请求 - C# application/x-www-form-urlencoded OAuth and HTTP REST requests using HttpClient 使用C#获取Webhooks以JSON形式获取内容类型为x-www-form-urlencode的请求消息 - Getting a request message with a content type x-www-form-urlencoded in a form of JSON using C# for webhooks 使用内容类型application / x-www-form-urlencoded解析从HTTP POST接收的C#中的JSON数据 - Parsing JSON data in C# received from HTTP POST with content-type application/x-www-form-urlencoded 尝试使用Content-Type application / x-www-form-urlencoded来访问API - Trying to reach API using Content-Type application/x-www-form-urlencoded 如何使用 HTTPclient content type = application/x-www-form-urlencoded POST - How to POST using HTTPclient content type = application/x-www-form-urlencoded 在WCF ReSTful服务中,POST或PUT请求的Content-Type是否需要为“ application / x-www-form-urlencoded”? - Does the Content-Type of a POST or PUT request need to be 'application/x-www-form-urlencoded' in a WCF ReSTful service? 使用 application/x-www-form-urlencoded 内容类型处理请求,但 NET Core 中的 XML 主体 Web API - Handle Request with application/x-www-form-urlencoded content-type but XML body in NET Core Web API 类型为“application/x-www-form-urlencoded”的 C# HttpWebRequest - 如何在内容正文中发送“&amp;”字符? - C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body? 如何以Content-Type的形式返回响应:application / x-www-form-urlencoded; 从WCF服务? - How to return response as Content-Type: application/x-www-form-urlencoded; from WCF service?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM