API响应始终为“null”。

huangapple go评论83阅读模式
英文:

API response is always "null"

问题

I created an API and a Login Form and I need to authorize access to my API using Username and Password properties, which I get from two textboxes in my Login Form. However, the response from the API is always null. Here's my original code:

public async Task<AuthenticatedUser> Authenticate(string username, string password)
{
    var data = new List<KeyValuePair<string, string>>()
    {
        new KeyValuePair<string, string>("grant_type", "password"),
        new KeyValuePair<string, string>("username", username), //I made sure that both username and password
        new KeyValuePair<string, string>("password", password)  //are passed correctly to the Authenticate() void
    };
    var content = new FormUrlEncodedContent(data); //var data is not null but "content" is
    using (HttpResponseMessage response = await apiClient.PostAsync("/token", content))
    {
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsAsync<AuthenticatedUser>(); //response is always "null"
            return result;
        }
        else
        {
            throw new Exception(response.ReasonPhrase);
        }
    }
}

I tried replacing the List<> with an array of KeyValuePair<>s, I also tried using a Dictionary<string, string>. Neither of these options worked. After some research on the net, I saw an alternative using StringContent or MediaFolder but I didn't know how to make it work with them.
I am also using https in my domain, so there seems to be no mistake there. For now, it looks as if FormUrlEncodedContent doesn't encode correctly.

Also, requests from Swagger and Postman return values.

英文:

I created an API and a Login Form and I need to authorize access to my API using Username and Password properties, which I get from two textboxes in my Login Form. However, the response from the API is always null. Here's my original code:

    public async Task&lt;AuthenticatedUser&gt; Authenticate(string username, string password)
    {
        var data = new List&lt;KeyValuePair&lt;string, string&gt;&gt;()
        {
            new KeyValuePair&lt;string, string&gt;(&quot;grant_type&quot;, &quot;password&quot;),
            new KeyValuePair&lt;string, string&gt;(&quot;username&quot;, username), //I made sure that both username and password
            new KeyValuePair&lt;string, string&gt;(&quot;password&quot;, password)  //are passed correctly to the Authenticate() void
        };
        var content = new FormUrlEncodedContent(data); //var data is not null but &quot;content&quot; is
        using (HttpResponseMessage response = await apiClient.PostAsync(&quot;/token&quot;, content))
        {
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync&lt;AuthenticatedUser&gt;(); //response is always &quot;null&quot;
                return result;
            }
            else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }
    }

I tried replacing the List&lt;&gt; with an array of KeyValuePair&lt;&gt;s, I also tried using a Dictionary&lt;string, string&gt;. Neither of these options worked. After some research on the net, I saw an alternative using StringContent or MediaFolder but I didn't know how to make it work with them.
I am also using https in my domain, so there seems to be no mistake there. For now, it looks as if FormUrlEncodedContent doesn't encode correctly.

Also, requests from Swagger and Postman return values.

答案1

得分: 1

我看到你完成了Tim Corey的YouTube频道上的教程,Retail Manager。我也遇到了PostAsync返回null的相同问题。

当你在代码行throw new Exception(response.ReasonPhrase);上设置断点时,可以查看异常详细信息。

在我的情况下,问题出在DataManager项目属性中的SSL启用设置为True,因此它使用安全协议(https)打开URL。在Tim的教程中,你可以看到使用http协议。

  • 在VS Solution Explorer中选择DataManager -> 属性 -> SSL启用: False
  • 右键单击DataManager -> 选择Web选项卡 -> 更改项目URL为: http://... 或选择覆盖应用程序根URL: http://...
  • 检查项目中的App.config文件: 在VS Solution Explorer中的DesktopUI中找到标签并更改key="api" value="http://..."
英文:

I see you did the tutorial from Tim Corey's youtube channel, Retail Manager. I also had the same issue with PostAsync returning null.

You can check exception details when you set breakpoint to line throw new Exception(response.ReasonPhrase);

In my case it was SSL endabled set to True in DataManager project properties, therefore it opens url with secure protocol - https. In Tim's tutorial you see http protocol.

  • Select DataManager in VS Solution Explorer -> Properties -> SSL Enabled: False
  • Right Click on DataManager -> select Web tab -> change project url to: http://... or select Override application root URL: http://...
  • Check App.config file in project: DesktopUI in VS Solution Explorer -> find tag and change key=&quot;api&quot; value=&quot;http://...

答案2

得分: 0

首先,password 授权类型只接受表单编码 application/x-www-form-urlencoded,而不是 JSON 编码 application/JSON

你可以在这里了解更多信息,并尝试按照以下方式更改内容:

用这个替换:

var data = new List<KeyValuePair<string, string>>()
{
    new KeyValuePair<string, string>("grant_type", "password"),
    new KeyValuePair<string, string>("username", username), //I made sure that both username and password
    new KeyValuePair<string, string>("password", password)  //are passed correctly to the Authenticate() void
};
var content = new FormUrlEncodedContent(data);

改为:

var content = new FormUrlEncodedContent(
    new KeyValuePair<string, string>[] {
        new KeyValuePair<string, string>("grant_type", "password"),
        new KeyValuePair<string, string>("username", username),
        new KeyValuePair<string, string>("password", password)
    }
);
英文:

First of all password grant type only accepts form encoding application/x-www-form-urlencoded and not JSON encoding application/JSON.

You can read more about it here and also try to change the content as follows:

Replace this:

var data = new List&lt;KeyValuePair&lt;string, string&gt;&gt;()
{
     new KeyValuePair&lt;string, string&gt;(&quot;grant_type&quot;, &quot;password&quot;),
     new KeyValuePair&lt;string, string&gt;(&quot;username&quot;, username), //I made sure that both username and password
     new KeyValuePair&lt;string, string&gt;(&quot;password&quot;, password)  //are passed correctly to the Authenticate() void
};
var content = new FormUrlEncodedContent(data);

with this:

var content = new FormUrlEncodedContent(
    new KeyValuePair&lt;string, string&gt;[] {
        new KeyValuePair&lt;string, string&gt;(&quot;grant_type&quot;, &quot;password&quot;),
        new KeyValuePair&lt;string, string&gt;(&quot;username&quot;, username),
        new KeyValuePair&lt;string, string&gt;(&quot;password&quot;, password)
   }
);

huangapple
  • 本文由 发表于 2020年1月3日 17:12:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定