C# adding authentication header to a webrequest

I have to be honest, some of these posts are more for my benefit that yours, so this is more of a reminder for me. In a recent project that called external web API’s extensively I needed to add an authentication header to some of the calls. I decided the best way was to extend the WebRequest (System.Net). We can do this easily with an extension method as shown below.

What are extension methods?

They are cool! Extension methods allow you to easily add methods to an existing type. You don’t need to create a derived type or any recompiling, they are great.

As you can see from the code above, an extension method is simply a special type of static but you would call one as though it was an instance method. You simply start by creating a static class. You then add any methods you like to extend the object. The methods must be marked as static and the first parameter needs to be the object you are extending, but you must put the word “this” before it. Now all you have to do is create an instance of the object and the extension method will be available to use. For example check this pseudo code.

Learning More

If you would like to learn more about extension methods, or C# in general, then I would recommend this book

It’s not just another book that takes you through the language and the .Net Framework. Jon Skeet selects an handful of the features of the C# language and takes you through them in great detail, but makes it easy to understand. I really not a fan of buying programming books because they are out of date before they even hit the shelves, but this one is well worth buying.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.