1

I'm trying to consume an API (tumblr) in an asp.net-mvc application and I feel like there should be a better and cleaner way to handle the response data.

I have these models:

public class TumblrEnvelope
{
    [JsonProperty("meta")]
    public TumblrMeta Meta { get; set; }

    [JsonProperty("response")]
    public dynamic Response { get; set; }
}

    public class TumblrBlogInfoResponse
{
    [JsonProperty("blog")]
    public TumblrBlog Blog { get; set; }
}

and I use them to catch response data in a service:

public TumblrBlog GetBlog(string blogIdentifier)
    {
        var requestUrl = "..."

        var envelope = GetResponse(requestUrl);

        if(envelope.Meta.IsSuccess)
        {
            return envelope.Response.ToObject<TumblrBlogInfoResponse>().Blog;
        }
        else
        {
            return null;
        }
    }

and I finally call it in a Controller like this

blog = _tumblrService.GetBlog(blogIdentifier);
if(blog == null)
{
    // something went wrong
}

Now the problem is that I can get a blog object back just fine, but if the request returned a bad response in the service, the Controller has no idea what happened, it just knows it didn't get a blog back.

I have to deserialize in two steps because I don't know the content of the Response property in advance and it has to be dynamic for this to work but intuitively it feels kind of wrong to do it this way. The API has dozens of different resources that can be queried and it seems bad to create a different model for each response and expecting the Controller to convert it.

Ideally I'd like to be able to return one standard result object that always contains the status code, optional error message and the statically typed object that you'd expect, but I don't know if it's possible to do that in a clean way.

I feel like there is probably a design pattern that can help me but I don't know what to look for.

  • The way you're doing it seems perfectly fine to me. If all those DTO classes bother you, deserialize into a dynamic variable instead. You'll lose compile-time type-safety, of course. – Robert Harvey Feb 4 '17 at 3:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.