Different from the previous httpwebrequest type, the httprequestheaders type in. Net 4.5 directly has an authorization attribute. The corresponding type is authenticationheadervalue, which is also in the system. net. http. headers namespace. Authenticationheadervalue has two attributes: parameter and scheme. To understand the role of these two parameters on the Authorization attribute, we can perform a simple test:
First, remember to add the corresponding httpclient namespace in. Net 4.5:
// + Using system. net. HTTP;
// + Using system. net. http. headers;
Set authenticationheadervalue in defaultrequestheaders, and then output the authorization value:
Using(VaR HTTP = New Httpclient())
{
HTTP.Defaultrequestheaders.Authorization = New Authenticationheadervalue("Mgen","Orca");
// Obtain the value through httpheaders. getvalues
Console.Writeline(String.Join(",",HTTP.Defaultrequestheaders.Getvalues("Authorization")));
}
Output:
Mgen orca
The original authorization attribute is set to scheme <space> parameter.
Therefore, you can use this method for basic verification:
Static Async Void Doo()
{
Using(VaR HTTP = New Httpclient())
{
Setbasicauthorization(HTTP.Defaultrequestheaders,"Mgen","123456",Encoding.Utf8);
// Subsequent operations are omitted
}
}
Static Void Setbasicauthorization(Httprequestheaders Header,String User,String Pass,Encoding Encoding)
{
// base64 encoding
var data = convert . tobase64string ( encoding . getbytes ( User + ": " + pass ));
// Set authenticationheadervalue
Header.Authorization = New Authenticationheadervalue("Basic",Data);
}
set authenticationheadervalue. Of course, the httprequestheader in. Net also allows you to directly modify the original HTTP header data through the httprequestheader. Add method. Of course, this is similar to the setting method of httpwebrequest before. Net 4.5:
Static Void Setbasicauthorization(Httprequestheaders Header,String User,String Pass,Encoding Encoding)
{
// base64 encoding
var data = convert . tobase64string ( encoding . getbytes ( User + ": " + pass ));
// Use httprequestheaders. Add
Header.Add("Authorization","Basic" + Data);
}
The authorization field of the HTTP request header is set as the basic authentication method.