C# · 12月 23, 2021

c# – 如何为现有的WCF服务本机启用JSONP?

我有一个现有的服务,如下面的方法: [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)][ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]public class SomeService : ISomething{ public SomeListResults SomeList(SomeParams someParams) { …. }}

是否有一种简单的方法可以同时允许JSONP调用和JSON(检测它).这是原生的吗?

解决方法 将配置更新为: <configuration> <system.web> <compilation debug=”true” targetframework=”4.0″> <authentication mode=”None”> </authentication></compilation></system.web> <system.webserver> <modules runallmanagedmodulesforallrequests=”true”> </modules></system.webserver> <system.servicemodel> <servicehostingenvironment **aspnetcompatibilityenabled**=”true”> <standardendpoints> <webscriptendpoint> <standardendpoint **crossdomainscriptaccessenabled**=”true” name=””> </standardendpoint></webscriptendpoint> </standardendpoints> </servicehostingenvironment></system.servicemodel></configuration>

See here for a blog post提供了创建可访问跨域的wcf服务的演练.

这将使您的服务能够接受来自跨域源的请求.

在确定是否填充您的响应(jsonp中的p)方面,

感谢@carlosfigueira:

If using .Net 4 JSONP is supported natively. As long as the request has a query string parameter called “callback” (this name can be configured),the response will be padded with the function name
.

否则,您需要编写一个自定义消息检查器,以适当地填充响应.