【问题标题】:Object reference not set to an instance of an object.??? in soap? [duplicate]你调用的对象是空的。???在肥皂里? [复制]
【发布时间】:2010-10-19 17:19:11
【问题描述】:

尝试调用网络服务时出错

“System.NullReferenceException:对象引用未设置为对象的实例。” 此行出错

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

这是什么意思?


[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";
        }
    }
}

【问题讨论】:

  • 可能Authentication 字段为空。但是 C# 中异常的好处是它们会告诉您失败的准确行号。这意味着什么?
  • 您是如何调用该服务的?你能发布那个代码吗?
  • @kirk,这一行出错“if (Authentication.Username == "x" && Authentication.Password == "y")"
  • 你能完成这项工作吗?如果是这样,您能否将答案标记为正确,或者发布您自己的答案并将其标记为正确,以便其他人知道什么有助于解决这个问题?谢谢!
  • NullReferenceException 的几乎所有情况都是相同的。请参阅“What is a NullReferenceException and how do I fix it?”获取一些提示。

标签: c# web-services soap asmx nullreferenceexception


【解决方案1】:

尝试将类 TestAuthHeader 的定义移到 Web 服务本身之外...

另外,尝试测试未知的标头,看看Authentication 是否会在那里结束...

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

除此之外,我们能否看到您调用 Web 服务的代码?

*编辑 *

如果您没有在客户端执行任何操作来创建 TestAuthHeader 的实例并设置其属性,那么您将在服务端获得一个空引用。来自使用 SoapHeaders 的 MSDN 示例(客户端代码):

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();


您真正需要的是:

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

    // ... the rest of your code

这将处理客户端未设置身份验证对象的情况。

【讨论】:

【解决方案2】:

我只是在猜测,但在您的 TestService 方法中,Authentication 实例可能为空,这给了您这个例外。也许您没有为该网站启用任何身份验证?

【讨论】:

  • 抱歉,这是什么意思?我必须打开身份验证?设置 web.config 以将其打开?不然不行吗?
猜你喜欢
  • 2012-01-02
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 2013-05-27
  • 2013-07-22
相关资源
最近更新 更多