如何使用HttpClient发布身份验证

编程入门 行业动态 更新时间:2024-10-22 13:30:41
本文介绍了如何使用HttpClient发布身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用HttpClient在C#中进行以下卷曲(对我有用)。

I am trying to do the following curl (which works for me) in C# using HttpClient.

curl -X POST www.somehosturl \ -u <client-id>:<client-secret> \ -d 'grant_type=password' \ -d 'username=<email>' \ -d 'password=<password>' \ -d 'scope=all

C#代码:

HttpClientHandler handler = new HttpClientHandler { Credentials = new System.Net.NetworkCredential ("my_client_id", "my_client_secret") }; try { using(var httpClient = new HttpClient(handler)) { var activationUrl = "www.somehosturl"; var postData = "grant_type=password&username=myemail@myemail&password=mypass&scope=all"; var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.PostAsync(activationUrl, content); if(!response.IsSuccessStatusCode) return null; var result = await response.Content.ReadAsStringAsync(); return result; } } catch(Exception) { return null; }

执行后,它崩溃了,甚至没有捕获到异常

When executed, just crashes out, doesnt even catch the exception

通常我能够进行GET和POST完全正常,但是让我失望的是如何设置身份验证内容(client-id和client-secret)

Normally I am able to GET and POST perfectly fine, but whats throwing me off is how to set the auth stuff (client-id and client-secret)

推荐答案

首先,必须使用<设置 Authorization -Header。 clientid> 和< clientsecret> 。

First you have to set the Authorization-Header with your <clientid> and <clientsecret>.

而不是使用 StringContent ,您应该使用 FormUrlEncodedContent ,如下所示:

Instead of using StringContent you should use FormUrlEncodedContent as shown below:

var client = new HttpClient(); client.BaseAddress = new Uri("myserver"); var request = new HttpRequestMessage(HttpMethod.Post, "/path"); var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); var formData = new List<KeyValuePair<string, string>>(); formData.Add(new KeyValuePair<string, string>("grant_type", "password")); formData.Add(new KeyValuePair<string, string>("username", "<email>")); formData.Add(new KeyValuePair<string, string>("password", "<password>")); formData.Add(new KeyValuePair<string, string>("scope", "all")); request.Content = new FormUrlEncodedContent(formData); var response = await client.SendAsync(request);

更多推荐

如何使用HttpClient发布身份验证

本文发布于:2023-11-03 16:18:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555554.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   身份验证   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!