获取请求无法在CORS中使用NancyFX

问题描述:

我遇到了一些CORS请求和NancyFx问题。 我有一些GET请求工作,但不是每次。获取请求无法在CORS中使用NancyFX

由于我使用Content-Type : application/json我的请求是“不是简单的请求类型”,所以他们有一个预检OPTIONS请求。

预检工作,但有时GET请求后返回404(没有找到我要求的路线),有时我得到我的数据。

这里是Nancyfx我CORS响应:

protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context) 
{ 
    base.RequestStartup(requestContainer, pipelines, context); 

    pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) => 
    { 
     ctx.Response.WithHeader("Access-Control-Allow-Origin", "*") 
     .WithHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS, PATCH") 
     .WithHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") 
     .WithHeader("Access-Control-Max-Age", "3600"); 
    }); 
} 

我打这样看的请求:

http://localhost:3579/api/v2/vnos/{idVno:guid}/vnos(和idVno始终设置)。

以下是我在控制台中看到:

enter image description here

,这里是我所得到的在网络选项卡:

enter image description here

而且只有特定的头我加入在我的客户端是Authorization标题。

应该在应用程序启动时调用OPTIONS处理程序,而不是像您那样请求启动,否则如果请求不是2XX,它将被忽略。

protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) 
{ 
    pipelines.AfterRequest += (ctx) => 
    { 
     ctx.Response.WithHeader("Access-Control-Allow-Origin", "*") 
        .WithHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS, PATCH") 
        .WithHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") 
        .WithHeader("Access-Control-Max-Age", "3600"); 
    } 
} 

查看https://github.com/NancyFx/Nancy/issues/1422了解更多信息。

+0

只有片段有助于解决,忘记添加它在'4xx'响应。谢谢思考 – mJehanno