.Net MVC C# HTTP Context

There is more than one way to get hold of the HTTP context in a controller:

    // Current via Controller context
    var ctr = ControllerContext;
    var contextBase = ctr.HttpContext.Request;

    // Get the request base
    var httpRequestBase = new HttpRequestWrapper(System.Web.HttpContext.Current.Request);

It’s going to be easier to unit test your code if you use ControllerContext.

.Net C# String encoding

A look at the various encoding systems available in .Net.

using System;
using System.Collections.Generic;
using System.Text;

namespace CharpStringDemo
{
    internal class CharpStringExample
    {
        private static IList<byte[]> _bytes;

        private static void Main()
        {
            _bytes = new List<byte[]>();
         
            const string input = "Csharp";   

            var result1 = Encoding.UTF7.GetBytes(input);
            _bytes.Add(result1);
            
            var result2 = Encoding.UTF8.GetBytes(input);
            _bytes.Add(result2);
            
            var result3 = Encoding.Unicode.GetBytes(input);
            _bytes.Add(result3);
            
            var result4 = Encoding.UTF32.GetBytes(input);
            _bytes.Add(result4);
            
            var result5 = Encoding.Default.GetBytes(input);
            _bytes.Add(result5);
            
            var result6 = Encoding.BigEndianUnicode.GetBytes(input);
            _bytes.Add(result6);
            
            var result7 = Encoding.ASCII.GetBytes(input);
            _bytes.Add(result7);

            foreach (var bytes in _bytes)
            {
                foreach (var code in bytes)
                {
                    Console.Write("{0} ", code);
                }

                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}

Returns:

67 115 104 97 114 112
67 115 104 97 114 112
67 0 115 0 104 0 97 0 114 0 112 0
67 0 0 0 115 0 0 0 104 0 0 0 97 0 0 0 114 0 0 0 112 0 0 0
67 115 104 97 114 112
0 67 0 115 0 104 0 97 0 114 0 112
67 115 104 97 114 112

.Net MVC C# OnActionExecuting example

A quick demo of how to hook up the OnActionExecuting method in an custom ActionFilter.

1) Create an ActionFilter class

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace CsharpWebAPIDemo.ActionFilters
{
    /// <summary>
    /// Custom action filter class for logging request variables
    /// </summary>
    public class LogActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            LogRequestVars("OnActionExecuting", filterContext);
        }

        /// <summary>
        /// Logs the request vars.
        /// </summary>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="values">The values.</param>
        private static void LogRequestVars(string methodName, ActionExecutingContext values)
        {
            // Get the request keys
            var keys = values.RequestContext.HttpContext.Request.Headers.AllKeys;

            // Get the request key value pairs
            var requestVars = keys.Select(key => new KeyValuePair<string, string>(key, values.RequestContext.HttpContext.Request.Headers.Get(key)));

            // Write to Debug log
            Debug.WriteLine("Method: {0}", methodName);

            foreach (var keyValuePair in requestVars)
            {
                Debug.WriteLine("{0} - {1}", keyValuePair.Key, keyValuePair.Value);
            }
        }
    }
}

2) Add the ActionFilter to you Controller class

using System.Web.Mvc;
using CsharpWebAPIDemo.ActionFilters;

namespace CsharpWebAPIDemo.Controllers
{
    public class HomeController : Controller
    {
        [LogActionFilter]
        public ActionResult Index()
        {
            return View();
        }
    }
}

The output is displayed in the output window of the debugger in Visual Studio.

.Net C# simple HttpListener

A simple example of a HttpListener class. Run the program and make a request in your web client.

i.e.

http://localhost:8080/
Then:
http://localhost:8080/go

using System;
using System.Net;

namespace CsharpListenerDemo
{
    static class CsharpListenerExample
    {
        static void Main()
        {
            var web = new HttpListener();

            web.Prefixes.Add("http://localhost:8080/");

            Console.WriteLine("Listening..");

            web.Start();

            Console.WriteLine(web.GetContext());

            var context = web.GetContext();

            var response = context.Response;

            const string responseString = "<html><body>Hello world</body></html>";

            var buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

            response.ContentLength64 = buffer.Length;

            var output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);

            Console.WriteLine(output);
            
            output.Close();

            web.Stop();

            Console.ReadKey();
        }
    }
}

Returns:

Hello World

.Net C# Force garbage collection

A quick post on how to force garbage collection to take place.

using System;

namespace CsharpForceGarbageCollectionDemo
{
    class CsharpForceGarbageCollectionExample
    {
        static void Main(string[] args)
        {
            //Create an anonymous object
            var obj = new {Name = "Object", Contains = new[] {"A","B"}};

            GC.Collect();

            GC.WaitForPendingFinalizers();

            Console.ReadKey();
        }
    }
}