[英]WCF error : 405 Method Not Allowed
为这个问题发疯。 我有一个包含 2 个项目的解决方案,其中一个是带有 jquery ajax 调用的普通旧 html,而另一个是 WCF 服务。 html 页面将向 WCF 服务发出 ajax 调用以获取 json 字符串并将其用于显示目的。
现在的问题是,每当我在调试模式下运行时,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 调用,并且绑定明确启用了跨域访问)。
...这样装饰的服务方法:
[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>
然而,它是一个旧线程,但我想添加我对我遇到的问题以及我为 CORS 工作获得的解决方案的评论。 我正在以下环境中开发 Web 服务:
大多数人提到在 web.config 中<webHttpBinding>
下的标记中添加crossDomainScriptAccessEnabled
属性。 我不确定这是否有效,但它在 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();
}
}
并从 web.config 中删除。 发布网站并继续客户端 jquery/ajax...您将从 api 调用中获取数据。 祝你好运!
只是想在底部附加一些与 CORS 返工有关的问题 - 它的问题是,如果您的输入不支持 GET 和 POST 方法,则 OPTIONS 请求实际上不会返回正确的允许标头。 它实际上并没有查看 WCF 端点上实际允许哪些方法——它只是人为地说当客户端执行 OPTIONS 请求时应用程序中的每个端点都允许“GET、POST”(这实际上是客户端询问什么支持)。
这可能没问题,如果你不是真的依赖 OPTIONS 方法中的信息来返回你一个有效的方法列表(就像一些 CORS 请求的情况一样) - 但如果你是,你将需要做一些事情这个问题的解决方案: How to handle Ajax JQUERY POST request with WCF self-host
基本上,每个端点都应该实现:
Webinvoke(Method="OPTIONS", UriTemplate="")
并调用适当的方法,将适当的标头加载到调用方的响应(包括该端点的适当的“Access-Control-Allow-Method”列表)。 托管 WCF 端点不会自动为我们执行此操作有点糟糕,但这是一种允许更好地控制端点的解决方法。 在该解决方案中,正确的响应标头在端点实现中加载:
public void GetOptions()
{
// The data loaded in these headers should match whatever it is you support on the endpoint
// for your application.
// For Origin: The "*" should really be a list of valid cross site domains for better security
// For Methods: The list should be the list of support methods for the endpoint
// For Allowed Headers: The list should be the supported header for your application
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
}
尝试使用。 WebInvoke(Method = "POST")
而不是WebInvoke(Method = "GET")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.