【问题标题】:Response.AsJson doen't work when calling it from a function in NancyFx从 NancyFx 中的函数调用 Response.AsJson 时不起作用
【发布时间】:2012-04-21 09:45:08
【问题描述】:

扩展方法:

Response.AsJson
Response.AsXml

从构造函数调用它时可以正常工作,例如:

public class TweetModule : NancyModule
    {
     public TweetModule()
            : base("/")
        {

            Post["/{action}.json/"] = parameters =>
            {
               return Reponse.Asjson(new {output:parameters.action}); // OK
            }
        }
     }   

但是当我从这样的函数中调用它时:

public class TweetModule : NancyModule
    {
     public TweetModule()
            : base("/")
        {

            Post["/{action}.{format}/"] = parameters =>
            {
               return GetResponse( parameters.action,parameters.format); // Error
            }
        }

        public Response GetResponse(string action,string format)
        {
           if (format == "json")
            return Response.AsJson(new {output:action}); // error
          else
            return Response.AsXml(new {output:action}); // error
        }


     }   

我得到了这个例外:

f__AnonymousType0`1[System.String] 无法序列化,因为它 没有无参数的构造函数。

有什么建议吗?

【问题讨论】:

    标签: asp.net c#-4.0 extension-methods anonymous-types nancy


    【解决方案1】:

    那很好用。问题是您捕获的参数称为 {fortmat} ,然后您传递 parameters.format 由于拼写错误而从未捕获

    我必须指出,您的代码甚至无法编译,因为 function 不是 C# 中的有效关键字,我只是假设您实际上是想说 public强> 代替。

    希望对你有帮助

    【讨论】:

    • 昨晚我在我的机器上试了一下,它工作了(使用 Nancy 的 0.10 nugets)。你传递了什么值来得到错误?你也在 ASP.NET 主机上运行吗?
    • 顺便说一句,你应该删除 :base("/") 调用,这是默认的隐式调用。
    猜你喜欢
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2017-04-11
    • 2016-08-29
    • 1970-01-01
    • 2021-12-28
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多