C# WCF MVC字段保持为空。。。为什么?

C# WCF MVC字段保持为空。。。为什么?,c#,asp.net-mvc,web-services,C#,Asp.net Mvc,Web Services,测试 public string username { get; set; } public void Test(string test) { this.username = test; } public string Get() { return this.username } [OperationContract] public string Get(); [OperationContract] public void Test(string test); va

测试

public string username { get; set; }
public void Test(string test)
{
    this.username = test;
}
public string Get()
{
     return this.username   
}
[OperationContract]
public string Get();

[OperationContract]
public void Test(string test);
var webapi3 = new v3.TestClient("BasicHttpBinding_IProductData1");
webapi3.Test("TestString");
var u = webapi3.Get();
ITest

public string username { get; set; }
public void Test(string test)
{
    this.username = test;
}
public string Get()
{
     return this.username   
}
[OperationContract]
public string Get();

[OperationContract]
public void Test(string test);
var webapi3 = new v3.TestClient("BasicHttpBinding_IProductData1");
webapi3.Test("TestString");
var u = webapi3.Get();
TestProject

public string username { get; set; }
public void Test(string test)
{
    this.username = test;
}
public string Get()
{
     return this.username   
}
[OperationContract]
public string Get();

[OperationContract]
public void Test(string test);
var webapi3 = new v3.TestClient("BasicHttpBinding_IProductData1");
webapi3.Test("TestString");
var u = webapi3.Get();
问题

为什么
u
仍然是空的,不知道我在尝试什么?

第二个调用
Get()
可能会在另一个线程上被拾取。如果要在服务器上显示状态,则需要将
username
设置为静态

您正在通过HTTP(一种无状态协议)进行通信

除了使字段为静态之外,还有其他选项,但这至少会使测试通过。

第二个调用
get()
可能会在另一个线程上被拾取。如果要在服务器上显示状态,则需要将
username
设置为静态

您正在通过HTTP(一种无状态协议)进行通信

除了使字段为静态之外,还有其他选项,但这至少会使测试通过。

公共无效测试(字符串测试) { this.username=test;//测试不是用户名吗? }

公共无效测试(字符串测试) { this.username=test;//测试不是用户名吗? }

我想

public void Test(string test)
{
   this.username = username;
}
应该是:

public void Test(string test)
{
   this.username = test;
}
我想

public void Test(string test)
{
   this.username = username;
}
应该是:

public void Test(string test)
{
   this.username = test;
}

我的问题有错。username设置为test,但仍然返回为空。我认为问题一定是您的服务是无状态的。这很好,因为有状态服务可能会将您带入一个问题的整个领域。但是,如果您必须具有状态(同样,我强烈建议您不要),请尝试添加
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
wsHttpBinding
绑定。或者作为更灵活的有状态替代方法,附加到持久数据存储,并让调用方在每次调用时提供令牌。这样,您就不会被锁定到
wsHttpBinding
。也许还有其他方法。我的问题是打字错误。username设置为test,但仍然返回为空。我认为问题一定是您的服务是无状态的。这很好,因为有状态服务可能会将您带入一个问题的整个领域。但是,如果您必须具有状态(同样,我强烈建议您不要),请尝试添加
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
wsHttpBinding
绑定。或者作为更灵活的有状态替代方法,附加到持久数据存储,并让调用方在每次调用时提供令牌。这样,您就不会被锁定到
wsHttpBinding
。也许还有其他方法。我的问题是打字错误。username设置为test,但在我的问题中仍然返回为emptyTypo。username设置为test,但仍然返回为空。使用单例而不是静态不是更好吗?@TheunArbeider单例如何更好?OP看起来像是测试代码,所以我假设线程同步不是问题所在。在真实场景中,状态将由状态存储(如数据库等)进行管理。使用单例而不是静态不是更好吗?@TheunArbeider单例究竟如何更好?OP看起来像是测试代码,所以我假设线程同步不是问题所在。在实际场景中,状态将由状态存储(如数据库等)管理。