AJAX DELETE不使用WebAPI - 发送OPTIONS以进行跨域请求

时间:2014-06-12 15:14:58

标签: jquery ajax asp.net-mvc asp.net-web-api asp.net-web-api2

我的AJAX请求:

        var options = {
            url: 'localhost:different/api/exercise/1',
            type: 'DELETE',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            }
        };

        return $.ajax(options)

WebAPI端点:

    [System.Web.Http.HttpDelete]
    [System.Web.Http.Route("api/exercise/{exerciseId}")]
    public HttpResponseMessage DeleteExercise(int exerciseId) {
        try {
            _adminService.DeleteExercise(exerciseId);
            return Request.CreateResponse(HttpStatusCode.OK, "Success");
        } catch (Exception e) {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
        }
    }

如果我通过POSTMAN chrome扩展程序发送相同的请求,则可以正常工作。

Web配置:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <httpProtocol>
      <customHeaders>
        <!-- TODO: don't let anyone make requests - only approved clients -->
        <add name="Access-Control-Allow-Origin" value="http://localhost:6263" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, X-Requested-With" />
        <add name="Access-Control-Allow-Credentials" value="true" />

        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <handlers>
      <remove name="WebDAV" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
  </system.webServer>

通过我的客户端在localhost上通过AJAX发送DELETE请求,我得到以下内容:

>  OPTIONS http://locaslhost:6273/api/exercise/2      XMLHttpRequest
> cannot load http://locaslhost:6273/api/exercise/2. Invalid HTTP status
> code 400

这就是Chrome所说的 - 请注意DELETE的访问控制请求方法,但请求方法是选项:

enter image description here

我还有另一个项目,我发誓以相同的方式设置它与CORS合作...我错过了什么?

0 个答案:

没有答案