Fellows! Today I am going to show you how you can add your custom headers to your web service requests. I have searched for it for a while in the past, lost my hope, forced my customers to write a new web service with a naive authentication.
But the thing we are going to accomplish is not easy at all.
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header> <AuthHeader xmlns="http://tempuri.org/"> <Username>string</Username> <Password>string</Password> </AuthHeader> </soap:Header> <soap:Body> <BolgeSorgu xmlns="http://tempuri.org/" /> </soap:Body> </soap:Envelope>
In here we see the soap envelope that we are going to send to get a response. I added the web service with Service References -> Add.
So this little cutie requires an auth header. This header requires Username and Password. So let's create a class contains those info.
[DataContract(Namespace = "http://tempuri.org/")] public class _ServiceCredential { [XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.None)] [DataMember(Order = 2)] public string Password; [DataMember(Order = 1)] [XmlAttribute(Form = System.Xml.Schema.XmlSchemaForm.None)] public string Username; }
So, the order was important in my case, I added it. Those XML Attributes were supposed to work, I did not want any namespaces on elements, but not working, darn.
So we create a static instance of our credentials;
public static _ServiceCredential ServiceCredential = new _ServiceCredential() { Username = "iphoneservs", Password = "sdfsdfssdfsdf" };That's also finished.
Only thing we need is to create the header and append to the request.
We are going to call a SOAP web service, generated from Visual Studio, so we are going to create it's client.
Service1.ServisSoapClient client = new Service1.ServisSoapClient();Then we need a event handlerclient.BolgeSorguCompleted += new EventHandler<Service1.BolgeSorguCompletedEventArgs>(client_BolgeSorguCompleted);Here it is.
So the modification we are going to make must be within a OperationContextScope. We create it from the channel of the client. This is how it goes:
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) { MessageHeader header = MessageHeader.CreateHeader("AuthHeader", "http://tempuri.org/",ServiceCredential ); OperationContext.Current.OutgoingMessageHeaders.Add(header); client.BolgeSorguAsync();}AuthHeader is the name of our header, tempuri is the namespace, service credential is the sh*t.
So that's how it goes fellows. Have fun with your custom credentials.
Hiç yorum yok:
Yorum Gönder