Link to home
Start Free TrialLog in
Avatar of MrMain
MrMain

asked on

SoapHeader Authentication of Webservice throws NullReferenceException ...

Hi,

I am attempting to pass a user id and pw in a Soapheader for my web service.  I am getting the following exception :

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.NullReferenceException: Object reference not set to an instance of an object. at ImageWebService..ctor() --- End of inner exception stack trace

I have used the SOAP Trace utlity to capture the SoapHeader, you can see that I have populated the username and password params.

<?xml version="1.0" encoding="utf-8" ?>
- <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <soap:Header>
- <AuthHeader xmlns="http://localhost/webservices/webservices">
  <Username>username</Username>
  <Password>password</Password>
  </AuthHeader>
  </soap:Header>
- <soap:Body>
  <GetTime xmlns="http://localhost/webservices/webservices" />
  </soap:Body>
  </soap:Envelope>


Here are the relevant parts of my webservice :

[WebService(Namespace="http://localhost/webservices/webservices")]
      public class WebService : System.Web.Services.WebService
      {
            public AuthHeader AuthenticationHeader;
....
public class AuthHeader : SoapHeader
{
    public string Username;
    public string Password;
}

[WebMethod, SoapHeader( "AuthenticationHeader" )]
public string GetTime()
{
    try
    {
         return DateTime.Now.ToString("HH.mm.ss.ffffff") + " Credentials : " + AuthenticationHeader.Username + ":" + AuthenticationHeader.Password;       
    }catch (Exception e) {
        return "Exception from GetTime()" + e.Message;
    }
}

My Client code :
    WebService myService = new WebService();
    AuthHeader objAuthHeader = new AuthHeader();
    objAuthHeader.Username = "username";
    objAuthHeader.Password = "password";
    myService.AuthHeaderValue = objAuthHeader;
    string message = myImgService.GetTime();


I am not sure why I am getting this exception, or how to fix it ?

Thanks.
Avatar of Thogek
Thogek
Flag of United States of America image

The inner exception message cites the constructor of an ImageWebService class, but I don't see that class mentioned anywhere else.  Does any of your code reference a class by this name?
Avatar of MrMain
MrMain

ASKER

Yeah - sorry, that is the name of my webservice, I just striped it out for the purpose of this question.  The actual client code is :

 Client code :
    ImageWebService myImgService = new ImageWebService();
    AuthHeader objAuthHeader = new AuthHeader();
    objAuthHeader.Username = "username";
    objAuthHeader.Password = "password";
    myImgService.AuthHeaderValue = objAuthHeader;
    string message = myImgService.GetTime();

The ImageWebService is the webservice that contains the SoapHeader Class and the GetTime() webmethod.
Is the ImageWebService class from a VS-generated Web Reference?
Did the error message include any suggestion of a line number within a specific file/class?

Your error message above:

    System.NullReferenceException: Object reference not set to an instance of an object. at ImageWebService..ctor()

seems to suggest that the error is occuring within the ImageWebService constructor (triggered at the "new ImageWebService();" statement)...
Avatar of MrMain

ASKER

I dont have Visual Studio .net, I used the wsdl utlity that comes with the .net sdk to create the ImageWebService Class. Then I built the ImageWebService  DLL and placed it in the same directory as my client, a C# windows application.  But all this was working fine before I added this SoapHeader stuff, the soap header call even worked fine the first time I ran it...  I'm not sure what I have done to break it?

The error occurs when I attempt to call the GetTime() webmethod.  This is the one that has the '[WebMethod, SoapHeader( "AuthenticationHeader" )]' reference.

This is the full exception below ... it looks to be something to do with the SoapHttpClientProtocol.Invoke() or SoapHttpClientProtocol.ReadResponse() methods ?


System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at ImageWebService..ctor()
   --- End of inner exception stack trace ---
   at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
   at SytekImageService.ImageWebService.GetTime()
   at WindowsApplication.Form1.btnUploadAlbum_Click(Object sender, EventArgs evArgs)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 1.0.5000.0
    Win32 Version: 1.1.4322.573
    CodeBase: file:///c:/windows/microsoft.net/framework/v1.1.4322/mscorlib.dll
----------------------------------------
WindowsApplication
    Assembly Version: 1.0.1764.11494
    Win32 Version: 1.0.1764.11494
    CodeBase: file:///C:/Documents%20and%20Settings/Nathan%20Main/My%20Documents/Dev/C%23/WebAlbum/Release/WindowsApplication.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 1.0.5000.0
    Win32 Version: 1.1.4322.573
    CodeBase: file:///c:/windows/assembly/gac/system.windows.forms/1.0.5000.0__b77a5c561934e089/system.windows.forms.dll
----------------------------------------
System
    Assembly Version: 1.0.5000.0
    Win32 Version: 1.1.4322.573
    CodeBase: file:///c:/windows/assembly/gac/system/1.0.5000.0__b77a5c561934e089/system.dll
----------------------------------------
System.Xml
    Assembly Version: 1.0.5000.0
    Win32 Version: 1.1.4322.573
    CodeBase: file:///c:/windows/assembly/gac/system.xml/1.0.5000.0__b77a5c561934e089/system.xml.dll
----------------------------------------
System.Drawing
    Assembly Version: 1.0.5000.0
    Win32 Version: 1.1.4322.573
    CodeBase: file:///c:/windows/assembly/gac/system.drawing/1.0.5000.0__b03f5f7f11d50a3a/system.drawing.dll
----------------------------------------
GlacialList
    Assembly Version: 1.0.1513.31776
    Win32 Version: 1.0.1513.31776
    CodeBase: file:///C:/Documents%20and%20Settings/Nathan%20Main/My%20Documents/Dev/C%23/WebAlbum/Release/GlacialList.DLL
----------------------------------------
ImageWebService
    Assembly Version: 0.0.0.0
    Win32 Version: 0.0.0.0
    CodeBase: file:///C:/Documents%20and%20Settings/Nathan%20Main/My%20Documents/Dev/C%23/WebAlbum/Release/ImageWebService.DLL
----------------------------------------
System.Web.Services
    Assembly Version: 1.0.5000.0
    Win32 Version: 1.1.4322.573
    CodeBase: file:///c:/windows/assembly/gac/system.web.services/1.0.5000.0__b03f5f7f11d50a3a/system.web.services.dll
----------------------------------------
System.Web
    Assembly Version: 1.0.5000.0
    Win32 Version: 1.1.4322.573
    CodeBase: file:///c:/windows/assembly/gac/system.web/1.0.5000.0__b03f5f7f11d50a3a/system.web.dll
----------------------------------------
kj9x8nz0
    Assembly Version: 0.0.0.0
    Win32 Version: 1.1.4322.573
    CodeBase: file:///c:/windows/assembly/gac/system/1.0.5000.0__b77a5c561934e089/system.dll
----------------------------------------

************** JIT Debugging **************
To enable just in time (JIT) debugging, the config file for this
application or machine (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:

<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the machine
rather than being handled by this dialog.
Well, the wsdl utlity and the VS.NET "Web Reference" both generate the same Web method proxy class...
I take it you didn't do anything to modify the class's code after generating it via wsdl?
Avatar of MrMain

ASKER

yeah - they would I guess.

I modified it once to capture the soap header to make sure I was sending the correct stuff.  But I re-create my proxy class with wsdl everytime I make a change to the webservice.  So any changes I made have long gone.
Avatar of MrMain

ASKER

This is my proxy class :

//------------------------------------------------------------------------------
// <autogenerated>
//     This code was generated by a tool.
//     Runtime Version: 1.1.4322.573
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------

//
// This source code was auto-generated by wsdl, Version=1.1.4322.573.
//
namespace SytekImageService {
    using System.Diagnostics;
    using System.Xml.Serialization;
    using System;
    using System.Web.Services.Protocols;
    using System.ComponentModel;
    using System.Web.Services;
   
   
    /// <remarks/>
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Web.Services.WebServiceBindingAttribute(Name="ImageWebServiceSoap", Namespace="http://localhost/webservices/webservices")]
    public class ImageWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
       
        public AuthHeader AuthHeaderValue;
       
        /// <remarks/>
        public ImageWebService() {
            this.Url = "http://localhost/webservices/ImageWebService.asmx";
        }
       
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://localhost/webservices/webservices/SaveImage", RequestNamespace="http://localhost/webservices/webservices", ResponseNamespace="http://localhost/webservices/webservices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public string SaveImage([System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] System.Byte[] aImage, string strAlbumPath, string strImageName) {
            object[] results = this.Invoke("SaveImage", new object[] {
                        aImage,
                        strAlbumPath,
                        strImageName});
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        public System.IAsyncResult BeginSaveImage(System.Byte[] aImage, string strAlbumPath, string strImageName, System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("SaveImage", new object[] {
                        aImage,
                        strAlbumPath,
                        strImageName}, callback, asyncState);
        }
       
        /// <remarks/>
        public string EndSaveImage(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://localhost/webservices/webservices/CreateDirectory", RequestNamespace="http://localhost/webservices/webservices", ResponseNamespace="http://localhost/webservices/webservices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public string CreateDirectory(string strDirectory) {
            object[] results = this.Invoke("CreateDirectory", new object[] {
                        strDirectory});
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        public System.IAsyncResult BeginCreateDirectory(string strDirectory, System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("CreateDirectory", new object[] {
                        strDirectory}, callback, asyncState);
        }
       
        /// <remarks/>
        public string EndCreateDirectory(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://localhost/webservices/webservices/UploadFile", RequestNamespace="http://localhost/webservices/webservices", ResponseNamespace="http://localhost/webservices/webservices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public string UploadFile([System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] System.Byte[] aFileBytes, string strPathToFile, string strFileName) {
            object[] results = this.Invoke("UploadFile", new object[] {
                        aFileBytes,
                        strPathToFile,
                        strFileName});
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        public System.IAsyncResult BeginUploadFile(System.Byte[] aFileBytes, string strPathToFile, string strFileName, System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("UploadFile", new object[] {
                        aFileBytes,
                        strPathToFile,
                        strFileName}, callback, asyncState);
        }
       
        /// <remarks/>
        public string EndUploadFile(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://localhost/webservices/webservices/Login", RequestNamespace="http://localhost/webservices/webservices", ResponseNamespace="http://localhost/webservices/webservices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public string Login() {
            object[] results = this.Invoke("Login", new object[0]);
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        public System.IAsyncResult BeginLogin(System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("Login", new object[0], callback, asyncState);
        }
       
        /// <remarks/>
        public string EndLogin(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        [System.Web.Services.Protocols.SoapHeaderAttribute("AuthHeaderValue", Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://localhost/webservices/webservices/GetTime", RequestNamespace="http://localhost/webservices/webservices", ResponseNamespace="http://localhost/webservices/webservices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public string GetTime() {
            object[] results = this.Invoke("GetTime", new object[0]);
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        public System.IAsyncResult BeginGetTime(System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("GetTime", new object[0], callback, asyncState);
        }
       
        /// <remarks/>
        public string EndGetTime(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://localhost/webservices/webservices/generateOID", RequestNamespace="http://localhost/webservices/webservices", ResponseNamespace="http://localhost/webservices/webservices", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
        public string generateOID() {
            object[] results = this.Invoke("generateOID", new object[0]);
            return ((string)(results[0]));
        }
       
        /// <remarks/>
        public System.IAsyncResult BegingenerateOID(System.AsyncCallback callback, object asyncState) {
            return this.BeginInvoke("generateOID", new object[0], callback, asyncState);
        }
       
        /// <remarks/>
        public string EndgenerateOID(System.IAsyncResult asyncResult) {
            object[] results = this.EndInvoke(asyncResult);
            return ((string)(results[0]));
        }
    }
   
    /// <remarks/>
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://localhost/webservices/webservices")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace="http://localhost/webservices/webservices", IsNullable=false)]
    public class AuthHeader : System.Web.Services.Protocols.SoapHeader {
       
        /// <remarks/>
        public string Username;
       
        /// <remarks/>
        public string Password;
    }
}
Avatar of MrMain

ASKER

I found the problem… I added the following to initialise a session variable :

public ImageWebService()
{                  
    // Initialize the logged in value to false.
    HttpContext.Current.Session["loggedIn"] = false;
}

If I remove the HttpContext line then it works, I dont know why though.

Thanks heaps for your time.
ASKER CERTIFIED SOLUTION
Avatar of Thogek
Thogek
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of MrMain

ASKER

Yeah - I looked into it.  You get a nullReferenceException if you dont add '[WebMethod(EnableSession=true)]' to your webmethod.  Since I was calling 'HttpContext.Current.Session["loggedIn"] = false;
' in my constructor that is why the exception was coming from there.  It was strange that my constructor was not called until I called the GetTime() test webmethod, and not when I was calling 'new' on the webservice proxy class???

Thanks again.
What SOAP Trace utlity did you use? Thanks for your help.
Avatar of MrMain

ASKER

I haven't done any of this kind of work for a little while, but I think what you need to do is turn on tracing or allow tracing to be displayed in your asp.net config file (web.config) in the same directory as your asp.net application. This should allow ASP.NET Tracing and exceptions to be displayed for the current asp.net application.