首页 > 解决方案 > Javascript Fetch 调用 WCF - 405(不允许的方法)

问题描述

学习 javascript,我在本地机器上运行了 WCF 服务。IIS 版本为 10。

我正在尝试通过在浏览器的控制台中使用 Javascript FETCH 来使用其中一种方法。承诺说“已实现”,但不允许使用该方法。谷歌搜索显示它与CORS相关,所以我在我的网站标题中添加了一个标题以允许(Access-Control-Allow-Origin *)。我无法编辑 WCF 的运营合同,因为我只是在托管它们(测试服务)。

有什么办法可以查看数据吗?我可以使用 WCF 测试客户端访问服务和方法。

我也尝试使用一些跨域代理,它可以工作,但是我如何查看 WCF 测试客户端输出的数据?

    async function test(){
     let s = await fetch('http://localhost/Main/Oriol.Host.BussServer/FinancialService.svc/GetAllTaxGroups',{
    method: 'GET', 
    cache: 'no-cache', 
    headers: {
      'Content-Type': 'application/json'   
    }})).then(a => a.json());
    console.log(s);
    }

编辑:

这是界面...

<service name="Oriol.Financial.Service.FinancialService" behaviorConfiguration="OriolServiceBehavior">
    <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web" bindingConfiguration="restWebHttpBinding" contract="Oriol.Financial.Domain.ServiceInterfaces.IFinancialService" />
    <endpoint address="soap" binding="basicHttpBinding" bindingConfiguration="OriolBasicHttpBinding" contract="Oriol.Financial.Domain.ServiceInterfaces.IFinancialService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
    <endpoint binding="netTcpBinding" bindingConfiguration="PortSharingBinding" contract="Oriol.Financial.Domain.ServiceInterfaces.IFinancialService" />
    <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" />
  </service>

这是 FinancialService.svc

<%@ ServiceHost Language="C#" Debug="true" Service="Oriol.Financial.Service.FinancialService" %>

错误:

GET http://localhost/Main/Oriol.Host.BussServer/FinancialService.svc/GetAllTaxGroups 405 (Method Not Allowed)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

谢谢

编辑:

这是回应:

Response {type: "cors", url: "http://localhost/Main/Oriol.Host.BussServer/FinancialService.svc/GetAllTaxGroups", redirected: false, status: 405, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 405
statusText: "Method Not Allowed"
type: "cors"
url: "http://localhost/Main/Oriol.Host.BussServer/FinancialService.svc/GetAllTaxGroups"
__proto__: Response

解析度:

在配置文件中添加。

<customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" /> 
</customHeaders>

此外,在 Fiddler 中仔细检查显示 Security 只允许 POST。除了方法之外,我不需要任何其他标头参数。

现在一切正常,谢谢大家。

标签: javascriptapiwcffetch

解决方案


推荐阅读