我正在尝试构建一个简单的Nancy self主机。如果我以正确的路径发送,我可以让它工作,但是如果我在port #之后发送空路径,我得到的是错误404。如果我发送了一个无效的路径,我会得到错误500。我想要的是有一个捕获所有的Get,当一个请求以无效的路径发送时就会使用它。
这是我的program.cs
using System.Diagnostics;
using Nancy;
using Nancy.Hosting.Self;
namespace NancyDataService
{
class Program
{
static void Main(string[] args)
{
var uri = new Uri("http://localhost:8080");
var hostConfig = new HostConfiguration();
hostConfig.UrlReservations.CreateAutomatically = true;
hostConfig.RewriteLocalhost = false;
using (var nancyHost = new NancyHost(uri, new DefaultNancyBootstrapper(), hostConfig))
{
nancyHost.Start();
Console.WriteLine("Nancy now listening on http://localhost:8080. Press enter to stop");
try
{
Process.Start("http://localhost:8080");
}
catch (Exception)
{
}
Console.ReadKey();
}
Console.WriteLine("Stopped. Good bye!");
}
}
}
下面是我的主要模块:
using Nancy;
namespace NancyDataService
{
public class MainModule: NancyModule
{
public MainModule()
{
string json_error = @"{""status"":""fail"",""reason"":""{0}""}";
string json;
Get("test", parms =>
{
return "test";
});
// this is default if desired path not sent
Get("{parm1}", parms =>
{
json = string.Format(json_error, "Invalid method name supplied");
//return (Response)json;
return json;
});
}
}
}
我已经更改了Get语法以匹配Nancy 2.0的方式。我希望上面代码中的最后一个Get会被处理,并给我一个默认的错误消息。如果我在浏览器中输入http://localhost:8080/
,我会得到错误404响应。如果我输入http://localhost:8080/test
,它就能正常工作。如果我进入http://localhost:8080/anythingElse
,我会得到错误500,内部服务器错误。
我想要的是有一个“默认”的get部分,这样在port #之后输入的任何意外路径(包括根本没有路径),它将采用该分支。
顺便说一句,这是针对.Net核心3.0,南希说这可能不会工作。我的Nancy.Hosting.Self包中的警告有一个警告,说它是使用.Net框架(4.6.1 - 4.8)恢复的。这可能是问题所在吗?
有什么好办法吗?谢谢..。
发布于 2020-05-30 02:28:24
解决了大部分问题。空路径需要Get("/", ...
,坏路径需要Get("/{parm}",...
。看起来string.Format
会导致错误500,但json_error.Replace("{0}", "new text")
工作得很好。这是怎么回事?
https://stackoverflow.com/questions/62076590
复制相似问题