Calling a Method with a SoapExtensionAttribute

2019-08-27 15:44发布

问题:

I have problem, I want set soap extension attribute in web method: Soap extension in web service:

public class EncryptMessageAttribute : SoapExtensionAttribute
{
    private string strKey="null";

    public void  setKey(string s)
    {
        strKey=s;
    }
}

Soap extension class:

public class EncryptMessage : SoapExtension
{
....
}

Soap extension on web method:

public class Service1 : System.Web.Services.WebService
{
    public string k;

    [WebMethod]
    [EncryptMessageAttribute(setKey(k))]
    public string test2()
    {
        return "ok";
    } 

    [WebMethod]
    [EncryptMessage(setKey(k))]
    public string test2()
    {
        return "ok";
    }
}

It finish with this compile error:

Error 1 The name 'setKey' does not exist in the current context Error 2 An object reference is required for the non-static field, method, or property

Update 1:

I tried:

public class Service1 : System.Web.Services.WebService
{
    public const string strAttribute = "something";

    [WebMethod]
    [EncryptMessage SetKey =strAttribute)]
    public string test2()
    {
        return "ok";
    }
}

It works. But I want want change attribute before the client call web method, it is possible, or the attribute must be const ?

For example: public string strAttribute does not work.

Update 2:

I have another question:

I have class, with variable num:

public class EncryptMessage : SoapExtension
{
    public int num=10;
    ....
}

Soap extension on web method:

public class Service1 : System.Web.Services.WebService
{
    public const string k = "something";

    /*in this place I want call some methods, which change variable num in class 
      EncryptMessage,
      before that is soap extension used on web method .. it is possible ?
      If yes, how can I change variable in class EncryptMessage
    */

    int num2 = 5;
    someMethods(num2); // this methods change variable num in class EncryptMessage

    [WebMethod]
    [EncryptMessage(SetKey =k)]
    public string test2()
    {
        return "ok";
    }
}

回答1:

You can't call a method on the attribute like you're doing

Use a property, not a method :

public class EncryptMessageAttribute : SoapExtensionAttribute
{
    private string strKey="null";

    public string Key
    {
        get { return strKey; }
        set { strKey = value; }
    }
}

[WebMethod]
[EncryptMessageAttribute(Key = "null")]
public string test2()
{
    return "ok";
}