Search code examples
asp.netc#-4.0extension-methodsanonymous-typesnancy

Response.AsJson doen't work when calling it from a function in NancyFx


The extension methods:

Response.AsJson
Response.AsXml

works fine when calling it from the constractor like:

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

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

But when I call it from a function like this:

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
        }


     }   

I get this exception:

<>f__AnonymousType0`1[System.String] cannot be serialized because it does not have a parameterless constructor.

any advice?


Solution

  • Na that works just fine. The problem is that your captured parameter is called {fortmat} and you then pass along parameters.format which is never captured due to the typo

    And I have to point out that your code won't even compile since function is not a valid keyword in C#, I just assumed that you actual meant it to say public instead.

    Hope this helps