Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

wpf - C# unsupported grant type when calling web api

I am trying to perform a Post to my WebAPI from a c# WPF desktop app.

No matter what I do, I get

{"error":"unsupported_grant_type"}

This is what I've tried (and I've tried everything I could find):

Also dev web api currently active for testing: http://studiodev.biz/

base http client object:

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("*/*"));

with the following send methods:

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");

After that failed, I did some googling and tried:

LoginModel data = new LoginModel(username, password);
string json = JsonConvert.SerializeObject(data);
await client.PostAsync("token", new JsonContent(json));

same result, so I tried:

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

Note: I can make a successful call with Chrome.

Update Fiddler Result

enter image description here

Could someone please help me make a successful call to the above web api... Please let me know if I can help clarify. Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The default implementation of OAuthAuthorizationServerHandler only accepts form encoding (i.e. application/x-www-form-urlencoded) and not JSON encoding (application/JSON).

Your request's ContentType should be application/x-www-form-urlencoded and pass the data in the body as:

grant_type=password&username=Alice&password=password123

i.e. not in JSON format.

The chrome example above works because it is not passing data as JSON. You only need this for getting a token; for other methods of your API you can use JSON.

This kind of problem is also discussed here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...