Ove*_*ars 60 c# wpf httpclient token asp.net-web-api
我正在尝试从ac#WPF桌面应用程序执行发布到我的WebAPI.
无论我做什么,我都会
{ "错误": "unsupported_grant_type"}
这就是我尝试过的(我已经尝试过所有可以找到的东西):
此外,dev web api目前正在进行测试:http://studiodev.biz/
基本http客户端对象:
var client = new HttpClient()
client.BaseAddress = new Uri("http://studiodev.biz/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
Run Code Online (Sandbox Code Playgroud)
使用以下发送方法:
var response = await client.PostAsJsonAsync("token", "{'grant_type'='password'&'username'='username'&'password'='password'");
var response = await client.PostAsJsonAsync("token", "grant_type=password&username=username&password=password");
Run Code Online (Sandbox Code Playgroud)
在那次失败后,我做了一些谷歌搜索并尝试:
LoginModel data = new LoginModel(username, password);
string json = JsonConvert.SerializeObject(data);
await client.PostAsync("token", new JsonContent(json));
Run Code Online (Sandbox Code Playgroud)
同样的结果,所以我试过:
req.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
await client.SendAsync(req).ContinueWith(respTask =>
{
Application.Current.Dispatcher.Invoke(new Action(() => { label.Content = respTask.Result.ToString(); }));
});
Run Code Online (Sandbox Code Playgroud)
注意:我可以通过Chrome成功拨打电话.
更新Fiddler结果
请有人帮我成功拨打上述网页API ...如果我能帮忙澄清,请告诉我.谢谢!!
M. *_*har 135
默认实现OAuthAuthorizationServerHandler
只接受表单编码(即application/x-www-form-urlencoded
)而不是JSON编码(application/JSON
).
您的请求ContentType
应该是application/x-www-form-urlencoded
并将正文中的数据传递为:
grant_type=password&username=Alice&password=password123
Run Code Online (Sandbox Code Playgroud)
即不是JSON格式.
上面的chrome示例有效,因为它没有将数据作为JSON传递.你只需要这个来获得一个令牌; 对于API的其他方法,您可以使用JSON.
这里也讨论了这种问题.
Chi*_*rag 14
1)注意URL:"localhost:55828/token"(不是"localhost:55828/API/token")
2)记下请求数据.它不是json格式,它只是没有双引号的普通数据."userName=xxx@gmail.com&password=Test123$&grant_type=password"
3)注意内容类型.内容类型:'application/x-www-form-urlencoded'(不是Content-Type:'application/json')
4)当您使用javascript发布帖子请求时,您可以使用以下内容:
$http.post("localhost:55828/token",
"userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password",
{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
).success(function (data) {//...
Run Code Online (Sandbox Code Playgroud)
请参阅Postman下面的截图:
Cas*_*ire 12
这是一个工作示例,我曾经使用SSL在端口43305上运行我的本地Web API应用程序的请求.我也把这个项目放在了GitHub上. https://github.com/casmer/WebAPI-getauthtoken
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;
using System.Web;
namespace GetAccessTokenSample
{
class Program
{
private static string baseUrl = "https://localhost:44305";
static void Main(string[] args)
{
Console.WriteLine("Enter Username: ");
string username= Console.ReadLine();
Console.WriteLine("Enter Password: ");
string password = Console.ReadLine();
LoginTokenResult accessToken = GetLoginToken(username,password);
if (accessToken.AccessToken != null)
{
Console.WriteLine(accessToken);
}
else
{
Console.WriteLine("Error Occurred:{0}, {1}", accessToken.Error, accessToken.ErrorDescription);
}
}
private static LoginTokenResult GetLoginToken(string username, string password)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
//TokenRequestViewModel tokenRequest = new TokenRequestViewModel() {
//password=userInfo.Password, username=userInfo.UserName};
HttpResponseMessage response =
client.PostAsync("Token",
new StringContent(string.Format("grant_type=password&username={0}&password={1}",
HttpUtility.UrlEncode(username),
HttpUtility.UrlEncode(password)), Encoding.UTF8,
"application/x-www-form-urlencoded")).Result;
string resultJSON = response.Content.ReadAsStringAsync().Result;
LoginTokenResult result = JsonConvert.DeserializeObject<LoginTokenResult>(resultJSON);
return result;
}
public class LoginTokenResult
{
public override string ToString()
{
return AccessToken;
}
[JsonProperty(PropertyName = "access_token")]
public string AccessToken { get; set; }
[JsonProperty(PropertyName = "error")]
public string Error { get; set; }
[JsonProperty(PropertyName = "error_description")]
public string ErrorDescription { get; set; }
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是RestSharp,则需要按以下方式发出请求:
public static U PostLogin<U>(string url, Authentication obj)
where U : new()
{
RestClient client = new RestClient();
client.BaseUrl = new Uri(host + url);
var request = new RestRequest(Method.POST);
string encodedBody = string.Format("grant_type=password&username={0}&password={1}",
obj.username,obj.password);
request.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);
request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
var response = client.Execute<U>(request);
return response.Data;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
57107 次 |
最近记录: |