无法解析$ http.put();访问控制允许来源

时间:2014-11-20 09:43:38

标签: javascript c# asp.net angularjs

我试图使用在MVC 4 .net WEB API中开发的休息服务。 $ http.get()和$ http.get(param)我没有任何问题。当我尝试$ http.put()时,我收到一个错误。好吧,我撒了谎。当我开始使用这个简单的项目时,我遇到了使用get方法的相同问题,我以这种方式管理它们:

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

现在似乎不起作用。这是angularjs控制台显示的错误:

http://i.stack.imgur.com/LEgwh.jpg

(我不能放图像,所以我放了一个链接)

我应该怎样做才能使用put方法?

1 个答案:

答案 0 :(得分:0)

您是否在web.config文件中启用了PUT?在开发期间,我看起来像这样。

<system.webServer>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
  <handlers>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <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>
</system.webServer>

另外,为了使用Web API启用PUT和DELETE谓词,您需要编辑可在%userprofile%\ documents \ iisexpress \ config \ applicationhost.config中找到的applicationhost.config文件,并且需要将动词添加到ExtensionlessUrl处理程序,以便您可以使用它们:

<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />