angularjs - 执行 PUT/POST 时没有 HTTP 资源错误 [CORS 问题 - AngularJS + Web API 2]

标签 angularjs asp.net-web-api cors put

有很多与此类似的问题,但没有一个解决了我的问题。

我有一个 angularjs 网站托管在 http://localhost:49595我正在调用托管在 http://localhost:63019 的 Web Api 2.1 服务.我在 web.config 中的 web api 服务器上启用了 CORS。请求 GET/buildings/1 和 GET/buildings/?$top=10&$skip=1 工作正常。

当涉及到 PUT 时,我收到以下错误:
{
"Message":"未找到与请求 URI 'http://localhost:63019/buildings/1105' 匹配的 HTTP 资源。",
"MessageDetail":"在 Controller 'Building' 上找不到与请求匹配的操作。"
}

Error in chrome

我可以看到浏览器将 OPTIONS 请求发送到服务器,但要更新的实际数据不在请求中(在 fiddler 中检查。不确定这对于 OPTIONS 查询是否正常。

enter image description here

我在 web api 上启用了跟踪,并看到以下日志。 https://gist.github.com/rnarayana/8905229 OPTIONS 请求(第 69 行)说它需要执行 PUT。在第 77 行附近,看起来它选择了正确的 Action 。然后 Controller 被处置。此外, Controller 被实例化了两次。

我怎样才能知道发生了什么?

在 AngularJS 中调用代码:
尝试:

$http.put('http://localhost:63019/buildings/' + building.BuildingId, building)
.then(onSuccess, onError);


$http({
    url: urlBase + '/' + building.BuildingId,
    dataType: 'json',
    method: 'PUT',
    data: building,
    headers: {"Content-Type": "application/json"}
}).then(onSuccess, onError);

这些在我的 Controller 中:
[HttpGet]
[Route("buildings/")]
public IHttpActionResult GetAll(ODataQueryOptions<BuildingViewModel> queryOptions)
{
}

[HttpGet]
[Route("buildings/{id}")]
public IHttpActionResult Get(long id)
{
}

[Route("buildings/")]
[HttpPost]
public IHttpActionResult Post(BuildingEditViewModel buildingEditViewModel)
{
}

[HttpPut]
[Route("buildings/{id}")]
public IHttpActionResult Put(long id, [FromBody]BuildingEditViewModel buildingEditViewModel)
{
}

//Added this as per some blog. Not helping.
[HttpOptions]
[Route("buildings/{id}")]
public HttpResponseMessage Options(long id)
{
    var response = new HttpResponseMessage();
    response.StatusCode = HttpStatusCode.OK;
    return response;
}

我的 webapi web.config 有:
<system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
          <remove name="WebDAVModule" />
        </modules>
        <handlers>
          <remove name="WebDAV" />
          <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
          <remove name="OPTIONSVerbHandler" />
          <remove name="TRACEVerbHandler" />
          <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="http://localhost:49595" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
            <add name="Access-Control-Allow-Headers" value="*" />
          </customHeaders>
        </httpProtocol>
    </system.webServer>

我的 WebApiConfig.Register() 有:
public static void Register(HttpConfiguration config)
    {
    config.EnableSystemDiagnosticsTracing();
    config.Services.Replace(typeof(ITraceWriter), new WebApiTracer());

    //Enable CORS. The allowed origins and verbs are in the config file. Do not add in both places.
    config.EnableCors();

    // Attribute routing.
    config.MapHttpAttributeRoutes();

    config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(
        config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault((t => t.MediaType == "application/xml")));
}

最佳答案

我在使用配置中的值时遇到问题,所以我从那里删除了它们,并将以下内容添加到我的 WebApiConfig 类中:

        //Specify values as appropriate (origins,headers,methods)
        var cors = new EnableCorsAttribute("http://myurl","*","*");
        config.EnableCors(cors);

您可以找到 Microsoft ASP.NET Web API 2.2 Cross-Origin 的 nuget 包来自 here

关于angularjs - 执行 PUT/POST 时没有 HTTP 资源错误 [CORS 问题 - AngularJS + Web API 2],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21664988/

相关文章:

javascript - 使用 json,php 时尝试获取非对象错误的属性

authentication - 如何使用 AngularJS ngView 为未经授权的用户隐藏模板?

c# - IIS Express 使用 CLI 信任自签名 SSL 证书

javascript - 无法从本地文件 :///nor from local web server 获取 XMLHttpRequest 的响应

css - Angular JS : Detect when page content has rendered fully and is visible

javascript - Angular js 在使用 foreach 完成多个 http 调用后回调

asp.net-mvc - 包括 XML 注释 – Swashbuckle

c# - 如何将 PDF 从 Web API 发送到 MVC 应用程序以供直接下载

javascript - XMLHttpRequest无法加载XXX No'Access-Control-Allow-Origin' header

cors - 为什么字体文件必须遵守 CORS 规则而图像不需要?