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

▼魔方 西西 提交于 2019-12-11 08:39:48

问题


In one project I'm using Nancy to serve basic web content via Nancy Self-Host. This generally works, but unfortunately, running queries on endpoints ie http://localhost/data.json results in the module receiving a request url of http://localhost/data.

When I query localhost/data.json I get a nancy-generated 404 response... in JSON. I have no clue why this is happening, and can't find this behavior documented anywhere.

Here's my module:

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

Here's how I start the server:

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

        _host.Start();

Any thoughts or suggestions would be greatly appreciated.


回答1:


According to #1919, #2671 and #2711 this is by design and you're unable to disable it:

This is a feature of content negotiation.

This happens for both .xml and .json.

Suggested workarounds would be to add something after the extension (GET /foo/bar.json/baz) or to rename the files (/foo/bar.js).




回答2:


You can override config, using this bootstrapper code:

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



来源:https://stackoverflow.com/questions/44462517/nancyfx-queries-to-json-files-stripping-the-json-extension-from-request-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!