FANDOM


WebAPI / Web API examples

Windows Service hosting WebAPIEdit

1.Edit

To support Windows Authorization, use NtlmSelfHostConfiguration instead of HttpSelfHostConfiguration

using System;
using System.Web.Http.SelfHost.Channels;
using System.ServiceProcess;
using System.Web.Http;
using System.Web.Http.SelfHost;
using System.ServiceModel.Channels;
using System.ServiceModel;

    public class NtlmSelfHostConfiguration : HttpSelfHostConfiguration
    {
        public NtlmSelfHostConfiguration(string baseAddress)
            : base(baseAddress)
        { }

        public NtlmSelfHostConfiguration(Uri baseAddress)
            : base(baseAddress)
        { }

        protected override BindingParameterCollection OnConfigureBinding(System.Web.Http.SelfHost.Channels.HttpBinding httpBinding)
        {
            httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;
            httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
            return base.OnConfigureBinding(httpBinding);
        }
    }


    public partial class AudioConverterTool : ServiceBase
    {
        NtlmSelfHostConfiguration _config;
        HttpSelfHostServer _server;
        private System.Diagnostics.EventLog _audioToolEventLog;

        public static AudioConverterTool Single { get; set; }

        public AudioConverterTool()
        {
            Single = this;

            InitializeComponent();

            // Logging events.
            if (!System.Diagnostics.EventLog.SourceExists("AudioToolSource"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                   "AudioToolSource", "AudioToolService");
            }
            _audioToolEventLog.Source = "AudioToolSource";
            _audioToolEventLog.Log = "AudioToolService";

            // Setting SelfHosted WebAPI
// You need to have appconfig section in your App.Config file:
/*
  <appSettings>
    <add key="ListeningURL_ServiceAddress" value="http://localhost:8080"></add>
  </appSettings>
*/
            var ServiceAddress = System.Configuration.ConfigurationManager.AppSettings["ListeningURL_ServiceAddress"];

            _audioToolEventLog.WriteEntry(string.Format("NtlmSelfHostConfiguration: Service Address: {0}", ServiceAddress));

            _config = new NtlmSelfHostConfiguration(ServiceAddress);
            // Set the max message size to 10M instead of the default size of 64k and also
            // set the transfer mode to 'streamed' so that don't allocate a 1M buffer but 
            // rather just have a small read buffer.
            _config.MaxReceivedMessageSize = 10 * 1024 * 1024;
            _config.TransferMode = TransferMode.Streamed;

            _config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            _audioToolEventLog.WriteEntry("WebAPI Routes Mapped");
        }

        protected override void OnStart(string[] args)
        {
            _audioToolEventLog.WriteEntry("Audio Tool Service - Starting...");

            this.RequestAdditionalTime(300000);

            _server = new HttpSelfHostServer(_config);

            _audioToolEventLog.WriteEntry("Opening Async connection");
            _server.OpenAsync();

            _audioToolEventLog.WriteEntry("Audio Tool Service - Started");
        }

        protected override void OnStop()
        {
            _audioToolEventLog.WriteEntry("Audio Tool Service - Stopping");

            _audioToolEventLog.WriteEntry("Closing Async connection");
            _server.CloseAsync().Wait();

            _audioToolEventLog.WriteEntry("Closed");
            _server.Dispose();

            _audioToolEventLog.WriteEntry("Audio Tool Service - Stopped");
        }

        protected override void OnContinue()
        {
            _audioToolEventLog.WriteEntry("Audio Tool Service - Continuing...");
        }

        protected override void OnPause()
        {
            _audioToolEventLog.WriteEntry("Audio Tool Service - Pausing...");
        }

        protected override void OnShutdown()
        {
            _audioToolEventLog.WriteEntry("Audio Tool Service - Shutting down...");
        }
    }

    public class NtlmSelfHostConfiguration : HttpSelfHostConfiguration
    {
        public NtlmSelfHostConfiguration(string baseAddress)
            : base(baseAddress)
        { }

        public NtlmSelfHostConfiguration(Uri baseAddress)
            : base(baseAddress)
        { }

        protected override BindingParameterCollection OnConfigureBinding(System.Web.Http.SelfHost.Channels.HttpBinding httpBinding)
        {
            httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;
            httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
            return base.OnConfigureBinding(httpBinding);
        }
    }

    partial class AudioConverterTool
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    }

2.Edit

using System;
using System.Net;
using System.Web.Http;

    [Authorize]
    public class ProductsController : ApiController
    {
        [HttpPost]
        public string Post(Newtonsoft.Json.Linq.JObject value)
        {
            try
            {
                string userName = base.User.Identity.Name;

                var audioFile = value.ToObject<AudioFile>();

                var audioAudioFile = CallSomeBusinessLogicToConvert(audioFile);

                var jo = Newtonsoft.Json.Linq.JObject.FromObject(audioFile);
                return jo.ToString();
            }
            catch (Exception e)
            {
                Program.Log(e.ToString());
                return "";
            }
        }

    public class AudioFile
    {
        public string Filename { get; set; }
        public byte[] FileContents { get; set; }
    }

Console client consuming WebAPIEdit

3.Edit

    class Program
    {
        static HttpClient client = new HttpClient();

        static void Main(string[] args)
        {
            var audioFile = new SecureAudio.AudioFile();

	// change this to whatever file you want to load.
            audioFile.Filename = "toad.png";
            audioFile.FileContents = File.ReadAllBytes(@"e:\temp\toad.png");

            string URI = "http://localhost:8080/api/products";

            Post(audioFile, URI);

            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }

        private static void Post(SecureAudio.AudioFile audioFile, string URI)
        {
            using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                wc.UseDefaultCredentials = true;

                var jo = Newtonsoft.Json.Linq.JObject.FromObject(audioFile);

                var rawResponse = wc.UploadData(URI, Encoding.Default.GetBytes(jo.ToString()));

                var sResponse = System.Text.Encoding.Default.GetString(rawResponse);
                var s = Regex.Unescape(sResponse).Trim('"');
                var jo2 = Newtonsoft.Json.Linq.JObject.Parse(s);
                var audioFile2 = jo2.ToObject<SecureAudio.AudioFile>();

                File.WriteAllBytes(@"e:\xx2.png", audioFile2.FileContents);
            }
        }
    }

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.