I tried doing the following but it not add the credential to the http header(SOAP Request).
MyWebService mySrv 开发者_C百科= new MyWebService();
System.Net.CredentialCache sysCredentail = new System.Net.CredentialCache();
NetworkCredential netCred = new NetworkCredential("admin", "password");
sysCredentail.Add(new Uri(strSysURL), "Basic", netCred);
mySrv.Credentials = sysCredentail;
I am expecting the following after adding credential information, when I call any webservice API.
SOAP::Transport::HTTP::Client::send_receive: POST http:/myurl/SYS HTTP /1.1
Accept: text/xml
Accept: multipart/*
Accept: application/soap
Content-Length: 431
Content-Type: text/xml; charset=utf-8
Authorization:: Basic YWRtaW46YnJvY2FkZQ==
SOAPAction: "urn:webservicesapi#getSystemName"
<?xml version="1.0" encoding="UTF-8"?>
etc...
but Authorization:: Basic YWRtaW46YnJvY2FkZQ== is missing even after adding the credential. Kindly advise.
Following the below steps had solved the issue.
1) Create a class derived from the webserivce class(auto generated class created after adding wsdl)
2) Override two functions GetWebRequest and SetRequestHeader.
3) Instead of creating the object of the webservice, create the object for the class which you created by Step 1.
4) Set the header information(credential information) using SetRequestHeader.
5) Access webservice API after step 4, it will work with authentication.
public class MyDerivedService : MyService { private String m_HeaderName; private String m_HeaderValue;
//----------------
// GetWebRequest
//
// Called by the SOAP client class library
//----------------
protected override WebRequest GetWebRequest(Uri uri)
{
// call the base class to get the underlying WebRequest object
HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(uri);
if (null != this.m_HeaderName)
{
// set the header
req.Headers.Add(this.m_HeaderName, this.m_HeaderValue);
}
// return the WebRequest to the caller
return (WebRequest)req;
}
//----------------
// SetRequestHeader
//
// Sets the header name and value that GetWebRequest will add to the
// underlying request used by the SOAP client when making the
// we method call
//----------------
public void SetRequestHeader(String headerName, String headerValue)
{
this.m_HeaderName = headerName;
this.m_HeaderValue = headerValue;
}
}
eg:
MyDerivedService objservice = new MyDerivedService ();
string usernamePassword = username + ":" + password;
objservice.SetRequestHeader("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
objservice.CallAnyAPI();
精彩评论