asp.net-mvc - 在 WCF 服务和 MVC 5 之间共享 HttpContext
问题描述
我用 MVC 5 和 WCF 创建了一个项目。我有一个带有AspNetCompatibilityRequirementsMode.Allowed的 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:
//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 服务器有能力识别客户端。它可以与从特定客户端发送到特定服务实例的所有消息相关联。
推荐阅读
- swift - 将模块映射用于 Swift 框架时,OpenSSL 库的非模块化标头
- javascript - create-react-app 安装,但无法使用“start”运行
- javascript - html 中真的需要 name 属性吗?
- python - 在时间序列数据上绘制买卖信号
- javascript - 控制台未加载
- python - 如何在 Python 中检索与某个值匹配的矩阵中元素的行号和列号?
- c++ - 检测 CListCtrl 列大小调整
- xml - 搜索目录和子目录以获取字符串列表和管道项目编号到文本文件
- angular - Angular 8:为什么每当复制它的数据更新时,我的不可观察类型就会更新?
- c# - 在实践中使用了多少对多关系?