执行PUT / POST时没有HTTP资源错误[CORS问题 - AngularJS + Web API 2] [英] No HTTP resource error when doing PUT/POST [CORS issue - AngularJS + Web API 2]

查看:391
本文介绍了执行PUT / POST时没有HTTP资源错误[CORS问题 - AngularJS + Web API 2]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这么多问题与SO类似,但没有一个问题解决了我的问题。

There are so many questions in SO similar to this, but none have fixed my issue.

我有一个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可以正常工作。

I've have an angularjs website hosted at http://localhost:49595 and I'm calling a Web Api 2.1 service hosted at http://localhost:63019. I've enabled CORS on the web api server in web.config. Requests for GET /buildings/1 and GET /buildings/?$top=10&$skip=1 work fine.

错误:
{
Message:找不到与请求URI匹配的HTTP资源 http:// localhost:63019 / buildings / 1105 '。,
MessageDetail:在与请求匹配的控制器Building上找不到任何操作。
}

When it comes to PUT, I get the following error: { "Message":"No HTTP resource was found that matches the request URI 'http://localhost:63019/buildings/1105'.", "MessageDetail":"No action was found on the controller 'Building' that matches the request." }

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

I can see the browser sends the OPTIONS request to the server, but the actual data to be updated is not in the request (checked in fiddler. Not sure if this is normal for an OPTIONS query.

我在网络API上启用了跟踪,我看到以下日志。 https://gist.github.com/rnarayana/8905229 OPTIONS请求(第69行)说它需要做一个PUT,在第77行,看起来它选择了正确的动作

I enabled tracing on the web api, and I see the following log. https://gist.github.com/rnarayana/8905229 The OPTIONS request (line 69) says it needs to do a PUT. Around line 77, it looks like it picked the correct action. And then the controller gets disposed. Moreover the controller is getting instantiated twice.

如何知道发生了什么?

在AngularJS中调用代码:
尝试:

Calling code in AngularJS: Tried:

$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);

这些都在我的控制器:

[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有:

My webapi web.config has:

<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()有:

My WebApiConfig.Register() has:

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类:

I had issues getting it to work with the the values in the config so I removed them from there and I added the following to my WebApiConfig class:

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

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

这篇关于执行PUT / POST时没有HTTP资源错误[CORS问题 - AngularJS + Web API 2]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆