简体   繁体   中英

How do I pass Basic Auth to a RESTful service in c#?

How do I call a RESTful service and pass in basic auth. This is username and password along with authorization basic.

 using (var httpClient = new HttpClient())
            {
                //var request = new StringContent(messageBody);
                //request.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                httpClient.BaseAddress = new Uri(serviceUrl);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var credentials = Encoding.ASCII.GetBytes("myadmin:mypassword");
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));

                //var response = await httpClient.PostAsJsonAsync(serviceUrl, customer);
                HttpResponseMessage response = await httpClient.PostAsJsonAsync("url here", customer);
            }

您必须用冒号连接用户名和密码,将值编码为base64,然后使用“基本”方案将此值添加到Authorization标头中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM