C# HttpClient PostAsync在获取令牌时返回500

C# HttpClient PostAsync在获取令牌时返回500,c#,api,httprequest,httpclient,httpresponse,C#,Api,Httprequest,Httpclient,Httpresponse,在阅读服务器日志之前,我正试图弄清楚我能做些什么(记录日志,需要检查的事情),因为我不想在请求之前错过一些愚蠢的事情 这是我的密码: const string URL = "https://SomeURL/api/security/"; string urlParameters = string.Format("grant_type=password&username={0}&password={1}", username, password); StringContent co

在阅读服务器日志之前,我正试图弄清楚我能做些什么(记录日志,需要检查的事情),因为我不想在请求之前错过一些愚蠢的事情

这是我的密码:

const string URL = "https://SomeURL/api/security/";
string urlParameters = string.Format("grant_type=password&username={0}&password={1}", username, password);
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded");

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
StringContent content = new StringContent(urlParameters, Encoding.UTF8, "application/x-www-form-urlencoded");

var tokenResponse = client.PostAsync("token", content).Result;

我对此有点新,所以我不确定下一步要检查什么,但我尝试了使用邮递员的相同请求,并用我的令牌获得了响应,因此看起来我缺少了一些内容,或者可能格式不正确?

我没有对我的参数进行URL编码,下面是修复方法(可能是更好的方法)


我没有对我的参数进行URL编码,下面是修复方法(可能是更好的方法)


我正在学习一门在线课程,设置URL参数的代码如下:

public async Task<AuthenticatedUser> Authenticate(string userName, string password)
    {
        var data = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username ", "userName"),
            new KeyValuePair<string, string>("password", "password")
        });

        using (HttpResponseMessage response = await apiClient.PostAsync("/Token", data))
        {
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<AuthenticatedUser>();
                return result;
            }
            else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }
    }
公共异步任务身份验证(字符串用户名、字符串密码)
{
var数据=新FormUrlEncodedContent(新[]
{
新的KeyValuePair(“授权类型”、“密码”),
新的KeyValuePair(“用户名”、“用户名”),
新的KeyValuePair(“密码”、“密码”)
});
使用(httpresponsemessageresponse=wait apiClient.PostAsync(“/Token”,data))
{
if(响应。IsSuccessStatusCode)
{
var result=await response.Content.ReadAsAsync();
返回结果;
}
其他的
{
抛出新异常(response.ReasonPhrase);
}
}
}
测试时,发现PostAsync呼叫返回了500个错误。我检查了我的URL地址和参数,它们看起来都是正确的。如果我在招摇过市中进行测试,那么我会收到一个200状态,并显示令牌

根据Thomas Levesque的链接,我更改了数据变量的设置方式:

var data = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "password",
            ["username"] = username,
            ["password"] = password
        });
var data=newformurlencodedcontent(新字典
{
[“授权类型”]=“密码”,
[“用户名”]=用户名,
[“密码”]=密码
});
现在,响应状态为200,已正确填充AuthenticatedUser模型。然而,我不明白为什么字典似乎有效,而KeyValuePair却无效。因此,我创建了列表,然后对其进行编码:

       var dataList = new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", username),
            new KeyValuePair<string, string>("password", password)
        };

        var content = new FormUrlEncodedContent(dataList);

        using (HttpResponseMessage response = await apiClient.PostAsync(requestUrl, content))
var dataList=new[]
{
新的KeyValuePair(“授权类型”、“密码”),
新的KeyValuePair(“用户名”,用户名),
新的KeyValuePair(“密码”,password)
};
var内容=新的FormUrlEncodedContent(数据列表);
使用(HttpResponseMessage response=wait apiClient.PostAsync(requestUrl,content))

这也起了作用。我坦率地承认,我还不完全理解为什么…。

我正在学习一门在线课程,设置URL参数的代码如下所示:

public async Task<AuthenticatedUser> Authenticate(string userName, string password)
    {
        var data = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username ", "userName"),
            new KeyValuePair<string, string>("password", "password")
        });

        using (HttpResponseMessage response = await apiClient.PostAsync("/Token", data))
        {
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<AuthenticatedUser>();
                return result;
            }
            else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }
    }
公共异步任务身份验证(字符串用户名、字符串密码)
{
var数据=新FormUrlEncodedContent(新[]
{
新的KeyValuePair(“授权类型”、“密码”),
新的KeyValuePair(“用户名”、“用户名”),
新的KeyValuePair(“密码”、“密码”)
});
使用(httpresponsemessageresponse=wait apiClient.PostAsync(“/Token”,data))
{
if(响应。IsSuccessStatusCode)
{
var result=await response.Content.ReadAsAsync();
返回结果;
}
其他的
{
抛出新异常(response.ReasonPhrase);
}
}
}
测试时,发现PostAsync呼叫返回了500个错误。我检查了我的URL地址和参数,它们看起来都是正确的。如果我在招摇过市中进行测试,那么我会收到一个200状态,并显示令牌

根据Thomas Levesque的链接,我更改了数据变量的设置方式:

var data = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "password",
            ["username"] = username,
            ["password"] = password
        });
var data=newformurlencodedcontent(新字典
{
[“授权类型”]=“密码”,
[“用户名”]=用户名,
[“密码”]=密码
});
现在,响应状态为200,已正确填充AuthenticatedUser模型。然而,我不明白为什么字典似乎有效,而KeyValuePair却无效。因此,我创建了列表,然后对其进行编码:

       var dataList = new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", username),
            new KeyValuePair<string, string>("password", password)
        };

        var content = new FormUrlEncodedContent(dataList);

        using (HttpResponseMessage response = await apiClient.PostAsync(requestUrl, content))
var dataList=new[]
{
新的KeyValuePair(“授权类型”、“密码”),
新的KeyValuePair(“用户名”,用户名),
新的KeyValuePair(“密码”,password)
};
var内容=新的FormUrlEncodedContent(数据列表);
使用(HttpResponseMessage response=wait apiClient.PostAsync(requestUrl,content))

这也起了作用。我坦率地承认,我还不完全理解为什么……。

500错误是服务器的错误,而不是客户端的错误。如果客户端出错,服务器应返回4xx错误。因此,您的请求中可能存在问题,但由于服务器无法正确处理,您无法知道它是什么。所以你必须看一下服务器日志。@ThomasLevesque,我用postman得到了一个成功的回复,这就是为什么我想发布这个问题,看看是否有;很明显我遗漏了什么。但是,是的,如果任何人都看不出来,我将不得不像你说的那样请求他们。尝试使用
FormUrlEncodedContent
,而不是
StringContent
:。此外,请记住,邮递员会隐式发送其他标题,例如
User Agent
Cookie
Accept Language
,等等。也许服务器正在等待这些标题。@ThomasLevesque,谢谢您的回复。我实际上是在寻找我可以尝试的想法,而这正是您的回答,因此非常感谢。您帮助我意识到我没有URL编码我的参数,服务器也在期待它。谢谢500错误是服务器的错误,而不是客户端的错误。如果客户端出错,服务器应返回4xx错误。因此,您的请求中可能存在问题,但由于服务器无法处理该问题