WCF错误:405方法不允许

ipo*_*fly 17 c# wcf jsonp cors

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

现在问题是每当我在调试模式下运行时,html页面和WCF都将以不同的端口启动.当我执行测试时(即在Firefox中调用类型= 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>
Run Code Online (Sandbox Code Playgroud)

任何人都有任何想法摆脱这个恼人的问题?

编辑:只是添加,我正在使用与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
}
Run Code Online (Sandbox Code Playgroud)

我的剧本:

$(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);

        }
    });
});
Run Code Online (Sandbox Code Playgroud)

Jud*_*her 10

您需要使用JSONP进行跨域调用以绕过浏览器限制,并使用crossDomainScriptAccessEnabled设置为true 更新web.config 以获取圆形服务器.答案中有一个很好的例子:如何避免使用jquery ajax中的跨域策略来使用wcf服务?

您可能还有GET请求问题.尝试这里概述的修复: 使WCF Web服务与GET请求一起工作

总而言之,您需要一个看起来像这样的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>
Run Code Online (Sandbox Code Playgroud)

(请注意,服务和端点都附加了行为,分别允许webHttp调用和httpGet调用,并且绑定具有显式启用的crossDomain访问权限).

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

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

...和使用JSONP的客户端调用:

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


Ram*_*mKr 8

然而它是一个旧的线程,但我想添加我对我遇到的问题的评论以及我为CORS工作所获得的解决方案.我正在以下环境中开发Web服务:

  1. WCF Web服务.
  2. .NET 3.5框架.
  3. 在现有的asp.net网站中添加了wcf web服务.
  4. Visual Studio 2008

大多数人提到在web.config crossDomainScriptAccessEnabled中添加标签下的属性<webHttpBinding>.我不确定这是否有效,但它在3.5版本中不可用,所以我别无选择.我还发现在web.config中添加以下标签将起作用...

<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>

但没有运气......继续得到405方法不允许错误

经过这些选项的苦苦挣扎后,我找到了另一种解决方案,可以根据下面的给定动态地在global.asax文件中添加这些头文件...

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}
Run Code Online (Sandbox Code Playgroud)

并从web.config中删除.发布网站并继续到客户端jquery/ajax ...然后你将从api调用中获取数据.祝好运!


aja*_*10d 7

对我有用的是启用 IIS 的 WCF 相关功能: 在此输入图像描述