获取南希请求信息

时间:2013-06-08 17:46:23

标签: c# sinatra nancy

我刚刚开始关注Nancy,我正在使用Tekpub的Sinatra Video(Nancy所基于的),看看它能做些什么。视频中演示的一件事是将请求信息输出回浏览器(请求方法,请求路径等)。当我使用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

1 个答案:

答案 0 :(得分:15)

你的意思是这样的吗?

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

相关问题