views:

69

answers:

2

Got an error while trying to invoke the webservice

"System.NullReferenceException: Object reference not set to an instance of an object." Error on this line

if (Authentication.Username == "x" &&
            Authentication.Password == "y")

what does this mean?


[WebService(Namespace = "https://domain.com")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Testing : System.Web.Services.WebService
{
    public TestAuthHeader Authentication;
    public class TestAuthHeader : SoapHeader
    {
        public string Username;
        public string Password;
    }

    [WebMethod]
    [SoapHeader("Authentication")]
    public string TestService()
    {
        if (Authentication.Username == "x" &&
            Authentication.Password == "y")
        {
            return "OK";
        }
        else
        {
            return "Access Denided";
        }
    }
}
A: 

I'm just guessing, but in your TestService method, the Authentication instance is probably null, giving you that exception. Maybe you don't have any authentication turned on for the site?

Coding Gorilla
Sorry but what does that mean? I have to turn on authentication ? Setup web.config to turn it on? Otherwise it wouldn't work?
K001
A: 

Try moving the definition of class TestAuthHeader outside of the web service itself...

Also, try testing unknown headers to see if Authentication is ending up there...

[WebMethod]
[SoapHeader("Authentication")]
[SoapHeader("unknownHeaders",Required=false)]
public string TestService()
{
   foreach (SoapUnknownHeader header in unknownHeaders) {
      // Test header
      Debug.Write(header.Element.Name);
   }
}

Other than that, can we see the code where you're calling into the web service?

*Edit *

If you're not doing anything on the client side to create an instance of TestAuthHeader and set its properties, you're going to have a null reference on the service side. From the MSDN example of using SoapHeaders (client code):

MyHeader mySoapHeader = new MyHeader();

// Populate the values of the SOAP header.
mySoapHeader.Username = Username;
mySoapHeader.Password = SecurelyStoredPassword;

// Create a new instance of the proxy class.
MyWebService proxy = new MyWebService();

// Add the MyHeader SOAP header to the SOAP request.
proxy.MyHeaderValue = mySoapHeader;

// Call the method on the proxy class that communicates with
// your Web service method.
string results = proxy.MyWebMethod();


All you really need is:

public string TestService()
{
    if (Authentication == null) {
        return "Access is denied";
    }

    // ... the rest of your code

This will handle the scenario of where the client doesn't set an authentication object.

James B
just using the default asm page to do involk, I was expecting the response to be "Access Denied"
K001