我用MVC 5和WCF创建了一个项目。我有一个 AspNetCompatibilityRequirementsMode.Allowed 以及W.Web服务
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
在MVC Controller中,我正在为会话添加价值
public class HomeController : Controller
{
ServiceReference1.MyService2Client ur = new ServiceReference1.MyService2Client();
public ActionResult Index()
{
HttpContext.Session.Add("UserId", 1);
ViewBag.msg = ur.Test();
return View();
}
}
在WCF服务中:
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService2 : IMyService2
{
private Test _test;
public MyService2(Test test)
{
_test = test;
}
public string Test()
{
var test = HttpContext.Current.Session["UserId"]; // Its Coming as NULL
return "Serivce Success";
}
}
即使我在MVC Controller中添加会话变量并尝试访问WCF服务中的会话变量,当请求到WCF服务时,会话变量也不存在。
在MVC web.config中:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IMyService2" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:30380/MyService2.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IMyService2" contract="ServiceReference1.IMyService2"
name="BasicHttpBinding_IMyService2" />
</client>
</system.serviceModel>
在WCF web.config中:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
帮我解决它
答案 0 :(得分:0)
wcf Web服务中没有httpcontext,
https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/wcf-services-and-aspnet
如文档所述,我们使用OperationContext。
https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.operationcontext?redirectedfrom=MSDN&view=netframework-4.7.2
如果要存储用户数据,则应启用WCF会话模式。
在这种情况下,WCF服务器可以识别客户端。它可以与从特定客户端发送到特定服务实例的所有消息关联。