0

I am working on an Azure Function app and want to have a bunch of methods that return a simple, strongly typed response which serializes to json in a simple way without using OkObjectResult due to it having too many extra properties that I don't need.

Example of desired output, where "Value" can become a complex type serialized to json:

{
    FooBar : Value
}

This is pretty easily achieved by using 'dynamic' keyword.

    [Function("CreateFooBar")]
    public async Task<dynamic> CreateFooBar([HttpTrigger(AuthorizationLevel.Anonymous, "post")]
        HttpRequestData req,
        FunctionContext executionContext)
    {
         return new
         {
             FooBar = "Value"
         }
    }

However, I don't want to have dynamic everywhere in my code. How can I make the below code actually work so it serializes using a key/value style mechanism? The JsonSerialization and ISerialization doesn't seem to provide an interface for this?

    public class OkResultWithValue 
    {
        public OkResultWithValue(string key,object value)
        {
           _key= key;
        }

        private string _key;
        public object  Value { get;  set ; }
    }

    [Function("CreateFooBar")]
    public async Task<OkResultWithValue> CreateFooBar([HttpTrigger(AuthorizationLevel.Anonymous, "post")]
        HttpRequestData req,
        FunctionContext executionContext)
    {
        object value = DoSomeThing();
        return new OkResultWithValue("FooBar",value)
    }

Now I can have all my Azure Functions return a strongly typed OkResultWithValue like this:

1 Answer 1

1

You can achieve the same with object instead:

[Function("CreateFooBar")]
public async Task<object> CreateFooBar([HttpTrigger(AuthorizationLevel.Anonymous, "post")]
    HttpRequestData req,
    FunctionContext executionContext)
{
     return new
     {
         FooBar = "Value"
     }
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, but I am hoping to have strong types so that it's easier to work with on the client consuming side as well. I want them to share these types via a published library for example. So I really want to do this without object or dynamic, basically, I want something similar to OKObjectResult which doesn't add its own properties and instead just serializes whatever I send it where I have full control of any additional properties it adds
OKObjectResult uses object to store the result, how is that any different?
OkObjectResult has a bunch of extra properties that I don't need that wind up in the json, e.g. Formatters and a few other things

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.