问题
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