【发布时间】: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