XMLHttpRequest无法加载URL。预检的响应具有无效的HTTP状态代码405

时间:2016-11-29 18:21:13

标签: asp.net vb.net iis

使用jquery ajax对IIS vb.net webservice进行简单的POST

<html>
    <head>
        <script type="text/javascript" src="./js/jquery-3.1.1.min.js"></script>
        <script type="text/javascript" src="./js/json-2.4.min.js"></script>
        <script type="text/javascript" src="./js/util.js"></script>
    </head>
    <body>
    <script type='text/javascript'>
        var myKeyVals = { userid : "USERID", password : "password", gkey : "key"}
        $.ajax({
            url: "myurl",
            type: "POST",
            data: JSON.stringify(myKeyVals),
            contentType: "application/json",
            cache: false,

            success: function( data, textStatus, jQxhr ){
                alert(JSON.stringify(data))
            },
            error: function( jqXhr, textStatus, errorThrown ){
                alert("error")
            }
        });
    </script>

    </body>
</html> 

它似乎与IE合作,但Chrome和Firefox抛出

&#34; XMLHttpRequest无法加载网址。预检的响应具有无效的HTTP状态代码405&#34;错误

我的web.config有

  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>

以及

<handlers>
     <remove name="OPTIONSVerbHandler" />
     <add name="OPTIONSVerbHandler" path="*" verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" preCondition="bitness32" />
</handlers>

根据许多其他帖子。

1 个答案:

答案 0 :(得分:0)

所以在我的情况下我没有global.asax所以我需要通过右键单击我的项目并添加一个新项目来创建一个。从那里你可以添加Global.asax。在Global.asax中,我必须在BeginRequest子

中执行以下操作
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        'HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        If HttpContext.Current.Request.HttpMethod = "OPTIONS" Then
            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")
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000")
            HttpContext.Current.Response.End()
        End If
    End Sub