【问题标题】:How to get token with C# WebApi Client (Owin)如何使用 C# WebApi Client (Owin) 获取令牌
【发布时间】:2018-11-26 00:28:01
【问题描述】:

我正在使用 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 helper 来实现这一点,下面是我尝试过的代码。

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

如果 (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; }

}

【问题讨论】:

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


    【解决方案1】:

    POST负载应该是查询字符串格式

    你需要把对象转换成这样的东西

    grant_type=password&amp;username=user_1&amp;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;
    

    【讨论】:

    • 很高兴为您提供帮助:)
    猜你喜欢
    • 2014-10-18
    • 1970-01-01
    • 2015-07-02
    • 2017-01-15
    • 2016-06-21
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2020-12-07
    相关资源
    最近更新 更多