Search code examples
jsonasynchronous.net-coretasknancy

How to remove Task json properties in Nancy.Response.AsJson


I've made one of my API endpoints and inner logic asynchronous and when previously I've used Response.AsJson(Foo.bar()) , it would return the json representation normally, but now I see this appended to it:

{
    "result": [
        {
            "id": "59d680cc734d1d08b4e6c89c",
            "properties": {
                "name": "value"
            }
        }
    ],
    "id": 3,
    "exception": null,
    "status": 5,
    "isCanceled": false,
    "isCompleted": true,
    "isCompletedSuccessfully": true,
    "creationOptions": 0,
    "asyncState": null,
    "isFaulted": false
}

But I want it to be like this:

    "id": "59d680cc734d1d08b4e6c89c",
        "properties": {
            "name": "value"
        }

As I understand, it's because I've wrapped my object in a Task , but I can't figure out, how with Nancy framework, which I use the Response.AsJson, to make it so the properties are excluded. I can obviously omit the Response.AsJson of the returned object, but then response is no longer Json if requesting through web-browser for example.

For further example

NancyModule for routing API:

public ItemCatalogModule(IItemCatalog itemCatalog) : base("/itemCatalog")
    {    
        Get("/fetch/{id}", async parameters =>
        {
            var id = (string)  parameters.id;
            var response = await Response.AsJson(itemCatalog.GetItem(id));
            return response;

        });
    }

How the interface looks like of ItemCatalog:

public interface IItemCatalog
{
    Task<Item> GetItem(string id);
}

Solution

  • You shoud do this :

    public ItemCatalogModule(IItemCatalog itemCatalog) : base("/itemCatalog")
    {    
        Get("/fetch/{id}", async parameters =>
        {
            var id = (string)  parameters.id;
            return Response.AsJson(await itemCatalog.GetItem(id));
    
        });
    }