最近在工作中使用Silverlight访问WCF报如下错误:System.Security.SecurityException: 安全性错误。经过资料查询,必须要在服务器端添加策略。
由于我使用的服务宿主程序为应用程序,所以将策略以文件流的形式承载在内存中。
来看策略服务代码:
using System.IO;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using Common.MessageGateway.Interfaces;
public class PolicyHepler
{
private PolicyHepler()
{
}
private static PolicyHepler _Instance;
public static PolicyHepler Instance
{
get
{
if ( _Instance == null )
{
_Instance = new PolicyHepler();
}
return _Instance;
}
}
public void LunchPolicy( string serviceUrl )
{
ServiceHost _policyhost = new ServiceHost( typeof( Policy ),new Uri( serviceUrl ) );
ServiceEndpoint endpoint = _policyhost.AddServiceEndpoint( typeof( ISilverlightService ),new WebHttpBinding(),string.Empty );
endpoint.Behaviors.Add( new WebHttpBehavior() );
_policyhost.open();
}
}
/// <summary>
/// 获取策略文件
/// </summary>
public class PolicyForHttp : ISilverlightService
{
public Stream GetClientAccesspolicy()
{
if ( WebOperationContext.Current != null )
{
WebOperationContext.Current.OutgoingResponse.Headers.Add( "Content-Type","text/xml;charset=utf-8" );
}
return Assembly.GetExecutingAssembly().GetManifestResourceStream( "AI3.Server.VSMServer.VSS.clientaccesspolicy.xml" );
}
}
#region nested type: Policy
/// <summary>
///获取策略文件流
/// </summary>
[ServiceBehavior( InstanceContextMode = InstanceContextMode.PerCall )]
public sealed class Policy : ISilverlightService
{
#region ICrossDomain Members
public Stream GetClientAccesspolicy()
{
if ( WebOperationContext.Current != null )
{
WebOperationContext.Current.OutgoingResponse.Headers.Add( "Content-Type","text/xml;charset=utf-8" );
}
const string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers=""*"">
<domain uri=""*""/>
</allow-from>
<grant-to>
<resource path=""/""
include-subpaths=""true""/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>";
var array = Encoding.Default.GetBytes( xml );
return new MemoryStream( array );
}
#endregion
}
#endregion
注意事项:发布策略服务的时候,IP和端口号和业务服务必须一致。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。