1

我正在尝试将用户信息从控制器传递到服务层。

IClientMessageInspectors并且IDispatchMessageInspectors似乎是最有可能的解决方案。

在完成了构建 HTTP 用户代理消息检查器编写 WCF 消息检查器之后,我对如何将信息添加到消息头以及如何读取它有了一个很好的了解。

我想不通的是:

如何获取用户信息IClientMessageInspector

在我曾经起诉过的控制器内部User.Identity.Name。但 User 对象在消息检查器中不可用。在消息检查器中获取此信息的一种方法是将其传递到构造函数中,但我从未显式创建 MessageInspector 对象,因此如何在其构造函数中传递用户信息。

编辑:我找到了第一个问题的答案。用户信息可以通过 System.Threading.Thread.CurrentPrincipal.Identity.Name 获取。仍然坚持第二部分。

如何在服务方法中提供用户信息?

我可以浏览标头并从 DispatchMessageInspector 中的消息标头中获取用户信息,但是如何在我的操作合同中提供这些信息?

4

1 回答 1

0

创建具有与用户信息相关的属性的类。使用此方法覆盖标头中的对象BeforeSendRequest(ref Message request, IClientChannel channel);方法设置值 -MessageHeader _messageHeader = MessageHeader.CreateHeader();并放入使用信息类的对象。

// Summary:
//     Creates a new message header with the specified data.
//
// Parameters:
//   name:
//     The local name of the header XML element.
//
//   ns:
//     The namespace URI of the header XML element.
//
//   value:
//     The content of the header to be created.
//
// Returns:
//     A System.ServiceModel.Channels.MessageHeader.
public static MessageHeader CreateHeader(string name, string ns, object value); 

在服务端获取它——MessageHeaders 类方法——

// Summary:
//     Finds a message header in this collection by the specified LocalName and
//     namespace URI of the header element.
//
// Parameters:
//   name:
//     The LocalName of the header XML element.
//
//   ns:
//     The namespace URI of the header XML element.
//
// Type parameters:
//   T:
//     The message header.
//
// Returns:
//     A message header.
public T GetHeader<T>(string name, string ns);
于 2012-06-26T14:14:44.117 回答