如何使用 C# WebApi Client (Owin) 获取令牌

How to get token with C# WebApi Client (Owin)

我正在使用 Owin.Oauth 进行授权。当我用邮递员发送这个参数时,我可以从 webapi 获取 json 数据。 url 是 http://localhost:53415/token

Headers (Key-Value)

Accept           application/json
Content-Type     application/x-www-form-urlencoded

Body

grant_type       password
username         user_1
password         123456

结果如下

{
    "access_token": "Q0G_r6iLTFk1eeZedyL4JC0Z6Q-sBwVmtSasrNm8Yb1MCscDkeLiXugKrXq236LEJK6vM8taXf9cfWhCKRTcBWrQ14x5FOFKE1oV5xdW8VKZL8LZSzsvEwzP5Rr7G4lnkakxcsbu151LkkmM_dIF3Rx9_cvk0z1TKUznm9Ke_jxKgjichd-8fmdsupmysuP00biNuT6PYZPHiMYXaON2YiCK67A1yGHb-X2GhBL6NWc",
    "token_type": "bearer",
    "expires_in": 86399
}

所以我正在尝试在 C# MVC 客户端中进行此操作。我创建了一个 api 助手来实现这个,下面是我尝试过的代码。

                ApiHelper<CampaignList> _api = new ApiHelper<CampaignList>();
                JObject oJsonObject = new JObject();
                oJsonObject.Add("grant_type", "password");
                oJsonObject.Add("username", "user_1");
                oJsonObject.Add("password", "123456");
                _api.GetToken(oJsonObject);

现在在 ApiHelper 中的代码是这样的:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(WebConfigurationManager.AppSettings["apiUrl"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
HttpResponseMessage response = client.PostAsJsonAsync("token", oJsonObject.ToString()).Result;
if (response.IsSuccessStatusCode)
   {
       ApiTokenEntity _entity = response.Content.ReadAsAsync<ApiTokenEntity>().Result;
       return _entity;
   }
   else
   {
       return null;
   }

if (response.IsSuccessStatusCode) 行 returned false 并且我无法将令牌发送到 return。所以我需要获取令牌以使用 header 发送。我dk哪里写错了。

public class ApiTokenEntity
{
    [JsonProperty(PropertyName = "access_token")]
    public string AccessToken { get; set; }

    [JsonProperty(PropertyName = "expires_in")]
    public int ExpiresIn { get; set; }

    [JsonProperty(PropertyName = "token_type")]
    public string TokenType { get; set; }

}

POST payload should be a query string format

您需要将对象转换成这样的形式

grant_type=password&username=user_1&password=123456

编写一个将您的对象转换为查询字符串参数的方法

public string GetQueryString(object obj) {
  var properties = from p in obj.GetType().GetProperties()
                   where p.GetValue(obj, null) != null
                   select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString());

  return String.Join("&", properties.ToArray());
}

// Usage:
string queryString = GetQueryString(foo);

参考here.

因为它是一个字符串,所以将 PostAsJsonAsync 更改为 PostAsync

所以你的实现应该是这样的

string result = GetQueryString(oJsonObject);
StringContent payload = new StringContent(result);
HttpResponseMessage response = client.PostAsync("token", payload).Result;