NancyFx 查询 JSON 文件,从请求 URL 中剥离 JSON 扩展名

NancyFx Queries to JSON files stripping the JSON extension from request URL

在一个项目中,我使用 Nancy 通过 Nancy Self-Host 提供基本的 Web 内容。这通常有效,但不幸的是,运行 对端点的查询即 http://localhost/data.json 导致模块收到 url 的 http://localhost/data 请求。

当我查询 localhost/data.json 时,我在 JSON 中收到 nancy 生成的 404 响应...我不知道为什么会这样,也找不到任何地方记录的这种行为。

这是我的模块:

public class NancySimpleWebModule : NancyModule
{
    /// <summary>
    /// TODO - HACK!
    /// </summary>
    public static NancySimpleWebServer WebServer;

    public NancySimpleWebModule()
    {
        Get["/"] = Get[@"/{url*}"] = _ =>
        {
            string filePath = WebServer.ResolveFilePath(Request.Url.Path.Trim('/', '\'));
            if (filePath == null || filePath.Length == 0 || !File.Exists(filePath))
                return new Response { StatusCode = HttpStatusCode.NotFound };

            return File.ReadAllText(filePath);
        };
    }
}

以下是我启动服务器的方式:

        _host = new NancyHost(
            new HostConfiguration { UrlReservations = new UrlReservations { CreateAutomatically = true } },
            uriToBind);

        _host.Start();

如有任何想法或建议,我们将不胜感激。

根据 #1919, #2671 and #2711 这是设计使然,您无法禁用它:

This is a feature of content negotiation.

.xml.json 都会出现这种情况。

建议的解决方法是在扩展名后添加一些内容 (GET /foo/bar.json/baz) 或重命名文件 (/foo/bar.js)。

您可以使用此引导程序代码覆盖配置:

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override NancyInternalConfiguration InternalConfiguration
    {
        get
        {
            return NancyInternalConfiguration.WithOverrides(x =>
            {
                // Otherwise '.xml' and '.json' will get stripped off request paths
                x.ResponseProcessors = new List<Type>
                {
                    typeof(ResponseProcessor),
                    typeof(ViewProcessor)
                };
            });
        }
    }
}

https://github.com/NancyFx/Nancy/issues/2671#issuecomment-349088969