A Simple Web API Helper

This post gives you the code to help you build an API url with the parameters and a quick way to call a simple get method and parse the results to the object you are expecting back from the API.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace SupplierPortal.Library.Helpers
{
    public class ApiHelper
    {
        public string BuildApiUrl(string domainAddress, string controllerName, string methodName, List<KeyValuePair<string, object>> parameters, string apiLocation)
        {
            StringBuilder url = new StringBuilder();
            url.Append($"{domainAddress}/{apiLocation}{controllerName}/{methodName}");
            if (parameters != null && parameters.Count > 0)
            {
                int parameterCount = parameters.Count;
                for (int i = 0; i < parameterCount; i++)
                {
                    url.Append(i == 0 ? "?" : "&");
                    url.Append($"{parameters[i].Key}={parameters[i].Value.ToString()}");
                }
            }
            return url.ToString();
        }

        public T GetResultFromApi<T>(string url)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                Task<String> response = httpClient.GetStringAsync(url);
                return Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(response.Result)).Result;
            }
        }
    }
}

Usage Example

And here is how you would call it.

using CodeShare.Library.Helpers;


var user = new HttpContextWrapper(HttpContext.Current).User; List<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>(); parameters.Add(new KeyValuePair<string, object>("username", user.Identity.Name)); parameters.Add(new KeyValuePair<string, object>("mediaPath", context.Request.FilePath)); ApiHelper apiHelper = new ApiHelper();
string url = apiHelper.BuildApiUrl( domainAddress: "http://www.example.com", apiLocation: "Umbraco/Api/", controllerName: "ProtectedMediaApi", methodName: "IsAllowed", parameters: parameters);
bool isAllowed = apiHelper.GetResultFromApi(url);

Want to thank me?

If I've helped you out and you want to thank me, why not buy me a coffee?

About the author

Paul Seal

Umbraco MVP and .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.

Related Posts

How to ignore a file locally in git without ignoring it from the repository

This post shows you how you can ignore a file in git locally without ignoring it from the repository…

Read Post

How to get the picked item name in Stacked Content and Nested Content using ncNodeName

This post shows you how you can get the name of the picked item in Nested Content or Stacked Content…

Read Post

How I use source control for my Umbraco website source code and media

In this post I share my approach to using source control for my Umbraco website source code and medi…

Read Post

How to solve the error "Could not load file or assembly 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0 ..."

This post will show you how to solve the error "Could not load file or assembly 'Microsoft.CodeDom.P…

Read Post