0

I was wondering if it is possible to serialise a Func or Action to JSON using either Json.Net or System.Text.Json in .Net Core with C#. I believe this was possible in .Net Framework but haven't found a way to do this in Core. It's not something I want to do but I wanted to check if it's something I need to protect against. For example would it be possible to have a standard API endpoint which accepted the following class as a parameter and could then execute the Func:

Example:

Class to be serialised:

public class TestClass
{
    public Func<string, string> Func { get; set; } = (name) => $"Hello {name}";
}

Client app:

public class TestClient() 
{
    public static async MainAsync()
    {
        var client = new HttpClient();
        var tc = new TestClass();
        var json = JsonConvert.SerializeObject(tc);        

        client.PostAsync(testServerUrl, new StringContent(json));
    }
}

Server app:

public class TestController
{
    [HttpPost]
    TestAction(TestClass containsFunc)
    {
        string myName = "TESTING"
        var myVar = containsFunc.Func(myName);
        // myVar = "Hello TESTING"
    }
}
SBFrancies
  • 3,987
  • 2
  • 14
  • 37
  • You mean to have the JSON contain C# source code? Or IL code? – Uwe Keim May 27 '21 at 14:54
  • I mean to have JSON containing whatever the representation of the Func is. So for example to serialise `(string name) => return $"Hello {name}";` then pass it to an API endpoint and execute the function in the API application. Sorry for not being clear, I will expand the question. – SBFrancies May 27 '21 at 14:56
  • 3
    Allowing a caller to cause your API to execute arbitrary code sounds like a security nightmare. You might consider having the API accept an option from a curated list instead. e.g. "dothing1" or "dothing2". – itsme86 May 27 '21 at 14:58
  • @itsme86 - I don't want to do it - I want to check if it's possible so that I can test against it if it is. I haven't been able to successfully JSON serialize a `Func` or `Action` so wanted to find out if it could be done so that if necessary I can code defensively. – SBFrancies May 27 '21 at 15:04
  • 1
    There's no way to serialize the actual code of a delegate. What actually gets serialized (with `BinaryFormatter`) is the secret compiler-generated class that actually implements the delegate and wraps its arguments. Problem is, the name of this class can easily change from build to build so serialized delegates can become corrupt and point to different methods on retrieval. See: [how come BinaryFormatter can serialize an Action<> but Json.net cannot](https://stackoverflow.com/a/49139733/3744182). – dbc Jun 03 '21 at 12:19

0 Answers0