我遇到了this 线程,我能够解决我的问题并将区域性名称传递给 DomainContext(客户端)向服务器发出的每个请求。
首先,我们需要创建一个自定义的 IClientMessageInspector,它负责为每个请求设置 CurrentUICulture 的参数。
public class AppendLanguageMessageInspector : IClientMessageInspector
{
#region IClientMessageInspector Members
public void AfterReceiveReply( ref Message reply, object correlationState )
{
// Nothing to do
}
public object BeforeSendRequest( ref Message request, IClientChannel channel )
{
var property = request.Properties[ HttpRequestMessageProperty.Name ] as HttpRequestMessageProperty;
if( property != null )
{
property.Headers[ "CultureName" ] = Thread.CurrentThread.CurrentUICulture.Name;
}
return null;
}
#endregion // IClientMessageInspector Members
}
接下来,我们需要创建一个自定义 WebHttpBehavior,它将注入我们的自定义 IClientMessageInspector。
public class AppendLanguageHttpBehavior : WebHttpBehavior
{
public override void ApplyClientBehavior( ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime )
{
clientRuntime.MessageInspectors.Add( _inspector );
}
private readonly AppendLanguageMessageInspector _inspector = new AppendLanguageMessageInspector();
}
最后,我们扩展客户端 DomainContext.OnCreate 方法来添加我们的自定义 WebHttpBehavior。 注意:扩展的 DomainContext 类的命名空间必须与生成的相同...
public partial class DomainService1
{
partial void OnCreated()
{
var domainClient = this.DomainClient as WebDomainClient<IDomainService1Contract>;
if( domainClient != null )
{
domainClient.ChannelFactory.Endpoint.Behaviors.Add( DomainService1.AppendLanguageHttpBehavior );
}
}
private static readonly AppendLanguageHttpBehavior AppendLanguageHttpBehavior = new AppendLanguageHttpBehavior();
}
现在,在服务器端,当我们想要获取语言代码时,我们可以像这样简单地访问它:
var cultureName = System.Web.HttpContext.Current.Request.Headers[ "CultureName" ];
要享受更多 DataAnnotation 的魔力,我们甚至可以像这样更改 DomainService 的 Initialize 中的 CurrentUICulture:
public override void Initialize( DomainServiceContext context )
{
var cultureName = System.Web.HttpContext.Current.Request.Headers[ "UICultureName" ];
Thread.CurrentThread.CurrentUICulture = new CultureInfo( cultureName );
base.Initialize( context );
}