c# - WCF 错误 : 405 Method Not Allowed

标签 c# wcf jsonp cors

对这个问题很生气。我有一个包含 2 个项目的解决方案,其中一个是带有 jquery ajax 调用的普通旧 html,而另一个是 WCF 服务。 html 页面将向 WCF 服务发出 ajax 调用以获取 json 字符串并将其用于显示目的。

现在的问题是,每当我在 Debug模式下运行时,html 页面和 WCF 都将使用不同的端口启动。这在我执行测试时为我创建了一个跨域问题(即在 Firefox 中调用 type = OPTIONS 时出现 405 Method Not Allowed 错误)。我会三次检查我的 ajax 脚本上的调用方法,WCF 服务是相同的 (GET)。

我会搜索谷歌,但发现我必须安装扩展或在 IIS 上执行一些配置,我发现这很麻烦,因为我正在做的事情很简单。按照一个示例,我将在我的 web.config 中添加以下配置,但它不起作用:

    <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="MobileService.webHttpBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="MyServiceBehavior">
          <serviceMetadata httpGetEnabled="true"  />
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="MobileService.SimpleMemberInfo" behaviorConfiguration="MyServiceBehavior">
        <endpoint address="" binding="webHttpBinding" contract="MobileService.IMemberInfo" bindingConfiguration="crossDomain" behaviorConfiguration="MobileService.webHttpBehavior">
        </endpoint>
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
    </system.webServer>

有人知道如何解决这个烦人的问题吗?

编辑:补充一下,我正在使用 VS Studio 2012 附带的 IIS Express 运行调试

添加 WCF 代码并更新 web.config

[ServiceContract]
public interface IMemberInfo
{
    [WebInvoke(Method = "GET",
           BodyStyle = WebMessageBodyStyle.Wrapped,
           ResponseFormat = WebMessageFormat.Json
    )]
    [OperationContract]
    string GetMemberInfoById();
    // TODO: Add your service operations here
}

我的脚本:

$(document).ready(function () {
    $.ajax("http://localhost:32972/SimpleMemberInfo.svc/GetMemberInfoById", {
        cache: false,
        beforeSend: function (xhr) {
            $.mobile.showPageLoadingMsg();
        },
        complete: function () {
            $.mobile.hidePageLoadingMsg();
        },
        contentType: 'application/json',
        dataType: 'json',
        type: 'GET',
        error: function () {
            alert('Something awful happened');
        },
        success: function (data) {
            var s = "";

            s += "<li>" + data + "</li>";
            $("#myList").html(s);

        }
    });
});

最佳答案

您需要使用 JSONP 进行跨域调用以绕过浏览器限制,并更新您的 web.config 并将 crossDomainScriptAccessEnabled 设置为 true 以绕过服务器限制。这里的答案中有一个很好的例子:how to avoid cross domain policy in jquery ajax for consuming wcf service?

您也可能遇到 GET 请求的问题。尝试此处列出的修复: Making a WCF Web Service work with GET requests

总而言之,您需要一个如下所示的 web.config:

<bindings>
  <webHttpBinding>
    <binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
  </webHttpBinding>
</bindings>
<behaviors>
  <endpointBehavior>
    <behavior name="restBehavior">
      <webHttp />
    </behavior>
  </endpointBehavior>
  <serviceBehavior>         
     <behavior name="MyServiceBehavior">
        <serviceMetadata httpGetEnabled="true"  />
        <serviceDebug includeExceptionDetailInFaults="true"/>
     </behavior>
  </serviceBehavior>
</behaviors>
<services>
  <service name="..." behaviorConfiguration="MyServiceBehavior">
    <endpoint address="" binding="webHttpBinding" bindingConfiguration="crossDomain" 
              contract="..." behaviorConfigurations="restBehavior" /> 
  </service>
</services>

(请注意,服务和端点都附加了行为,分别允许 webHttp 调用和 httpGet 调用,并且绑定(bind)明确启用了跨域访问)。

...这样装饰的服务方法:

[ServiceContract]
public interface IMyService
{
    [WebGet] // Required Attribute to allow GET
    [OperationContract]
    string MyMethod(string MyParam);
}

...以及使用 JSONP 的客户端调用:

<script type="text/javascript">
$(document).ready(function() {
    var url =  "...";
    $.getJSON(url + "?callback=?", null, function(result) { // Note crucial ?callback=?
       // Process result
    });
});
</script>

关于c# - WCF 错误 : 405 Method Not Allowed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13228995/

相关文章:

c# - WPF 颜色选择器 - 添加新的自定义颜色

c# - 如何在我的 asp net core 3.1 Controller 中的特定操作上设置基本身份验证?

c# - PHP根据主机名获取IP

WCF-认证客户端是否需要服务证书?

asp.net - 自承载 WCF 服务中的 Autofac 对象生命周期范围

php - 跨域 ajax 和 php session

c# - 在c#上创建一个空心矩形

c# - 从 .NET 使用 SAP Web 服务会抛出异常 ServiceModel.FaultException

angularjs - AngularJS 中的 401 未经授权的错误处理

javascript - 如何修复我的代码中的 getJSON 方法错误?