Thursday, December 19, 2019

Make a dumb .NET Framework 4.7.2 API to test an Angular application with in Visual Studio 2017!

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
namespace DumbApi.Controllers
{
   public class ValuesController : ApiController
   {
      public HttpResponseMessage Get()
      {
         DateTime immediacy = DateTime.UtcNow;
         List<Tuple<string, int>> tuples = new List<Tuple<string, int>>()
         {
            new Tuple<string, int>("foo", immediacy.Day),
            new Tuple<string, int>("bar", immediacy.Hour),
            new Tuple<string, int>("baz", immediacy.Minute),
            new Tuple<string, int>("qux", immediacy.Second)
         };
         HttpConfiguration config = new HttpConfiguration();
         config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
            new MediaTypeHeaderValue("text/html")
         );
         var response = Request.CreateResponse(HttpStatusCode.OK, tuples, config);
         response.Headers.Add("Access-Control-Allow-Origin", "*");
         return response;
      }
   }
}

 
 

What is above will spit out something like this:

[
   {"m_Item1":"foo","m_Item2":19},
   {"m_Item1":"bar","m_Item2":15},
   {"m_Item1":"baz","m_Item2":32},
   {"m_Item1":"qux","m_Item2":16}
]

No comments:

Post a Comment