我有一个用角度编写的客户端应用程序,可以将请求发布到connect/token
const body = new HttpParams()
.set('username', email)
.set('password', password)
.set('grant_type', "password")
.set('scope', "offline_access");
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<any>(this._baseAuthUrl + 'connect/token', body, { headers })
现在我必须用C#编写此文件,但有一部分卡住了
HttpClient httpClient = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
如何添加HttpParams
并正确发布请求?
答案 0 :(得分:0)
这是代码。
var httpClient = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("scope", "offline_access")
};
var content = new FormUrlEncodedContent(pairs);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
requestMessage.Content = content;
var response = await httpClient.SendAsync(requestMessage);
以上代码仅是回答问题的示例。但是在实现中,应该使用HttpClient static并立即对其进行初始化。 Read more