您有几个选项可以通过 webHttpBinding 启用 JSONP:
如果您想使用WebServiceHostFactory,您可以在该工厂创建的default 端点中更改crossDomainScriptAccessEnabled 属性的默认值。这可以通过将以下部分添加到您的配置来完成:
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true"
defaultOutgoingResponseFormat="Json"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
如果您不想更改应用程序中所有 Web 服务主机的默认设置,那么您可以仅对您的应用程序进行更改。一种替代方法是使用自定义服务主机工厂,它将根据需要设置端点:
public class MyFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
return new MyServiceHost(serviceType, baseAddresses);
}
class MyServiceHost : ServiceHost
{
public MyServiceHost(Type serviceType, Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{
}
protected override void OnOpening()
{
// this assumes the service contract is the same as the service type
// (i.e., the [ServiceContract] attribute is applied to the class itself;
// if this is not the case, change the type below.
var contractType = this.Description.ServiceType;
WebHttpBinding binding = new WebHttpBinding();
binding.CrossDomainScriptAccessEnabled = true;
var endpoint = this.AddServiceEndpoint(contractType, binding, "");
var behavior = new WebHttpBehavior();
behavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
endpoint.Behaviors.Add(behavior);
}
}
}
另一种选择是通过配置定义端点:
<system.serviceModel>
<services>
<service name="StackOverflow_14280814.MyService">
<endpoint address=""
binding="webHttpBinding"
bindingConfiguration="withJsonp"
behaviorConfiguration="web"
contract="StackOverflow_14280814.MyService" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="withJsonp" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>