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"
}
}