Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Tuesday, 6 February 2018

Make REST service



Controllers inherit from ApiController


Methods return an IHttpActionResult


Use the helper stuff to return good or bad results


Creating a Web API project will include MVC stuff, but you don't need it. Can create an Empty project and just add in Web API. Include the MVC stuff to get views etc. You can include if you want to make a nice homepage for your REST service with some cat pictures on it?

.Net consume REST using HttpClient

Create HttpClient and setup in the constructor


Make requests as required. Use .Result after the post to make life synchronous.


Pull info from the response if needed, use Newtonsoft.Json to deserialize to objects.


Stuff, stuff, stuff



    public class AwesomeService : IAwesomeService
    {
        private static HttpClient _client;

        public AwesomeService()
        {
            if (_client == null)
            {
                // trust all certificates
                System.Net.ServicePointManager.ServerCertificateValidationCallback =
                    ((sender, certificate, chain, sslPolicyErrors) => true);
               
                _client = new HttpClient();
                var baseUrl = ConfigurationManager.AppSettings["ServiceBaseUrl"];
                _client.BaseAddress = new Uri(baseUrl);
                _client.DefaultRequestHeaders.Accept.Clear();
                _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }
        }

        public void DoThing(string from, string to)
        {
            var paramTemplate = ConfigurationManager.AppSettings["ParamTemplate"] ?? "v1.0/email?from={1}&to={2}";
            var path = string.Format(paramTemplate, from, to);
            HttpResponseMessage response = _client.PostAsync(path, null).Result;
            response.EnsureSuccessStatusCode();
        }
}


        public string GetFullname(string userName)
        {
            var pathTemplate = ConfigurationManager.AppSettings["ActiveDirectoryUserTemplate"] ?? "v1.0/user?userId={0}";
            var path = string.Format(pathTemplate, userName);
            string fullName = null;
            HttpResponseMessage response = _client.GetAsync(path).Result;
            if (response.IsSuccessStatusCode)
            {
                var json = response.Content.ReadAsStringAsync().Result;
                fullName = JsonConvert.DeserializeObject<string>(json);
            }

            return fullName;
        }