如何使用C#WebApi客户端(Owin)获取令牌

时间:2018-06-16 12:10:12

标签: c# asp.net-web-api json.net client owin

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

标题(键值)

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

车身

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)行返回false并且我无法获取我的令牌返回。所以我需要获得令牌以发送标头。我在哪里犯错了。

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; }

}

1 个答案:

答案 0 :(得分:1)

  

POST 有效负载应为查询字符串格式

您需要将对象转换为类似

的对象

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;