在 WCF 服务和 MVC 5 之间共享 HttpContext



我用MVC 5和WCF创建了一个项目。我有一个带有AspNetCompatibility RequirementsMode.Allow的WCF服务,也在web.config中

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />

在MVC控制器中,我正在为会话增加价值

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 控制器中添加会话变量并尝试访问 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>

帮我解决它

wcf Web 服务中没有
httpcontext,https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/wcf-services-and-aspnet
正如文档提到的,我们使用 OperationContext。
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.operationcontext?redirectedfrom=MSDN&view=netframework-4.7.2
如果要存储用户数据,则应启用 WCF 会话模式。 在这种情况下,WCF 服务器可以标识客户端。它可以与从特定客户端发送到特定服务实例的所有消息相关联。

https://social.msdn.microsoft.com/Forums/vstudio/en-US/27896125-b61e-42bd-a1b0-e6da5c23e6fc/httpcontextcurrent-in-wcf

最新更新