3

我刚开始研究南希,我正在使用来自 Tekpub 的 Sinatra 视频(南希所基于的),看看它可以做什么。视频中演示的一件事是将请求信息输出回浏览器(请求方法、请求路径等)。当我使用 ASP.Net Web Forms 时,我可以在 Request 对象中获取该信息,但我没有在文档中看到任何内容,这些信息向我展示了如何在 Nancy 中执行此操作。我知道 Nancy.Request 对象中有一个 Headers 字段,但它并没有提供我正在寻找的所有信息。下面是我想转换为 C# 和 Nancy 的原始 Sinatra 代码:

class HelloWorld
     def call(env)
          out = ""
          env.keys.each {|key| out+="#{key}=#{env[key]}"}
          ["200",{"Content-Type" => "text/plain"}, out]
     end
 end

 run HelloWorld.new
4

1 回答 1

18

你的意思是这样的?

Get["/test"] = _ =>
{
    var responseThing = new
    {
        this.Request.Headers,
        this.Request.Query,
        this.Request.Form,
        this.Request.Session,
        this.Request.Method,
        this.Request.Url,
        this.Request.Path
    };

    return Response.AsJson(responseThing);
};

这会给你一个像这样的输出:

{
   "Form":{

   },
   "Headers":[
      {
         "Key":"Cache-Control",
         "Value":[
            "max-age=0"
         ]
      },
      {
         "Key":"Connection",
         "Value":[
            "keep-alive"
         ]
      },
      {
         "Key":"Accept",
         "Value":[
            "text/html;q=1",
            "application/xhtml+xml;q=1",
            "application/xml;q=0.9",
            "*/*;q=0.8"
         ]
      },
      {
         "Key":"Accept-Encoding",
         "Value":[
            "gzip,deflate,sdch"
         ]
      },
      {
         "Key":"Accept-Language",
         "Value":[
            "en-US,en;q=0.8"
         ]
      },
      {
         "Key":"Host",
         "Value":[
            "localhost:2234"
         ]
      },
      {
         "Key":"User-Agent",
         "Value":[
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36"
         ]
      }
   ],
   "Method":"GET",
   "Path":"/test",
   "Query":{
      "23423":"fweew"
   },
   "Session":[

   ],
   "Url":{
      "BasePath":null,
      "Fragment":"",
      "HostName":"localhost:2234",
      "IsSecure":false,
      "Path":"/test",
      "Port":null,
      "Query":"23423=fweew",
      "Scheme":"http",
      "SiteBase":"http://localhost:2234"
   }
}

您还可以在此处的 wiki 中获取 Owin 环境变量

https://github.com/NancyFx/Nancy/wiki/Hosting-nancy-with-owin#accessing-owin-environment-variables

于 2013-06-08T18:36:12.670 回答