VB.NET Web API CORS PUT预检405错误

时间:2014-12-06 08:32:29

标签: javascript jquery vb.net asp.net-web-api cors

我正在使用启用了CORS的WEB API和我的GET& POST工作正常。但是我的PUT没有通过CORS工作。我可以在Chrome中使用“高级REST”扩展程序并且工作正常。我在网络配置中包含各种设置

更新:我想要注意我的POST正在通过CORS工作。其中,如果我理解该过程首先发送一个OPTION动词。 OPTION动词通过,但是PUT却没有。

更新2:因此看起来PUT(OPTIONS)动词需要预检。我在想我没有那个,我真的找不到如何做到这一点。

<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<remove name="WebDAV" />
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>

$.ajax({
    type: "PUT",
    dataType: "json",
    url: url,
    contentType: "application/json",
    data: newMod,
    success: function (data) {
        OutfitModelKey = data;
        console.log(data);
        console.log(OutfitModelKey);
        if (callback) {
            callback();
        }
    },
    error: function (error) {
        alert("hi, error");
        //jsonValue = jQuery.parseJSON(error.responseText);
        //console.log(jsonValue);
        //ToastDanger("uh o!", jsonValue);
        //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
    }
});

' PUT api/OutfitModel/5
Public Function PutOutfitModel(ByVal id As Integer, <FromBody()> ByVal value As PhotoModelManagerCL.objOutfitModel) As Boolean
    value.OutfitModelKey = id
    Dim success As Boolean = PhotoModelManagerCL.UpdateobjOutfitModelByKey(value)
    Return success
End Function

Advanced REST extention in Chrome showing the PUT call working

Chrome console showing the PUT/OPTION fail. After gets work.

1 个答案:

答案 0 :(得分:3)

看起来指定方法明确修复了问题

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

对于PUT动词,还有一个预先请求(有些人称之为预检):Options

要处理它,您需要发回空响应。你可以在你的行动中做到这一点,或者你可以像这样在全球范围内做到这一点:

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    If Request.Headers.AllKeys.Contains("Origin") And Request.HttpMethod = "OPTIONS" Then
        Response.Flush()
    End If
End Sub

C#等价物

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}