Sorted By: Month (10) and Year (2012)

Working with IIS Express Self-signed Certificate, ASP.NET Web API and HttpClient

We will see how to smoothly work with IIS Express Self-signed Certificate, ASP.NET Web API and HttpClient by placing the self-signed certificate in the Trusted Root CA store.
2012-10-23 19:34
Tugberk Ugurlu


If you would like to only support HTTPS with your ASP.NET Web API application, you might also want expose your application through HTTPS during the development time. This is not a big problem if you are heavily integration-testing your Web API as you can pass anything you want as a host name but if you are building your HTTP API wrapper simultaneously, you want to sometimes do manual testing to see if it’s actually working. There are sevaral ways to sort this problem out and one of them is provided directly by Visual Studio. Visual Studio allows us to create HTTPS bindings to use with IIS Express during development time. Let’s see how that works.

Note: I am assuming everybody understands that I am talking about ASP.NET Web API web host scenario with ASP.NET here. This blog post is not about self-host scenarios.

First of all, I created an empty web application through visual studio. Then, I added one of my NuGet packages: WebAPIDoodle.Bootstrap.Sample.Complex. This package will get you all ASP.NET Web API stuff and a working sample with all CRUD operations.

I also created a message handler which is going to ensure that our API is only going to be exposed over HTTPS.

public class RequireHttpsMessageHandler : DelegatingHandler {

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken) {

        if (request.RequestUri.Scheme != Uri.UriSchemeHttps) {

            var forbiddenResponse = 
                request.CreateResponse(HttpStatusCode.Forbidden);

            forbiddenResponse.ReasonPhrase = "SSL Required";
            return Task.FromResult<HttpResponseMessage>(forbiddenResponse);
        }

        return base.SendAsync(request, cancellationToken);
    }
}

Then, I registered this message handler as you can see below:

protected void Application_Start(object sender, EventArgs e) {

    var config = GlobalConfiguration.Configuration;

    //...

    config.MessageHandlers.Add(new RequireHttpsMessageHandler());
}

To configure the HTTPS endpoint with IIS Express, I simply need to click on the web application project and press F4. This will bring up the project properties and there will be a option there called "SSL Enabled".

image

By default, this is set to False as you can see. If we change this and set it to True, Visual Studio will create the necessary binding for our application by assigning a new port number and attaching the pre-generated self-signed certificate for that endpoint.

image

Now, when we open up a browser and navigate to that HTTPS endpoint, we should face a scary looking error:

image

As our certificate is a self-signed certificate, the browser doesn’t trust that and gives this error. This error is not a blocking issue for us and we can just click the Proceed anyway button to suppress this error and everything will be work just fine.

Let’s close the browser and create a very simple and naïve .NET console client for our API as below:

class Program {

    static void Main(string[] args) {

        Console.WriteLine(GetStringAsync().Result);
        Console.ReadLine();
    }

    public static async Task<string> GetStringAsync() {

        using (HttpClient client = new HttpClient()) {

            return await client
               .GetStringAsync("https://localhost:44304/api/cars");
        }
    }
}

As I said, it is insanely simple Smile but will serve for our demo purposes. If we run this console application along with our Web API application, we should see an exception thrown as below:

image

This time the HttpClient is nagging at us because it didn’t trust the server certificate. If we open up the browser again and take a look at the certificate, we will see that it is also complaining that this self-signed certificate is not in the Trusted Root CA store.

image

One way to get rid of this problem is to place this self-signed certificate in the Trusted Root CA store and the error will go away. Let’s first open up a PowerShell Command window and see where this self-signed certificate lives.

image

As we now know where the certificate is, we can grab this certificate and place it in the Trusted Root CA store. There are several ways of doing this but I love PowerShell, so I am going to do this with PowerShell, too. To be able to perform the below operations, we need to open up an elevated PowerShell Command Prompt.

image

Let’s explain what we did above:

  • We retrieved our self-signed certificate and stuck it into a variable.
  • Then, we retrieved the Trusted Root CA store and stuck that into a variable, too.
  • Lastly, we opened up the store with Read and Write access and added the certificate there. As a final step, we closed the store.

After this change, if we take a look at the Trusted Root CA store, we will see our certificate there:

SNAGHTML1d009a0f

If we now run our console client application, we should see it working smoothly.

image

I hope this will help you as much as it helped me Smile

Newsflash! ASP.NET Web API does not Sit on Top of ASP.NET MVC! In Fact, It does not Sit on Top of Anything

One of the common misconceptions about ASP.NET Web API is that it is being built on top of ASP.NET MVC. Today, I am going to break it!
2012-10-20 08:57
Tugberk Ugurlu


One of the common misconceptions about ASP.NET Web API is that it is being built on top of ASP.NET MVC (particularly ASP.NET MVC 4). In my opinion, the distribution of ASP.NET Web API along with ASP.NET MVC installer has the biggest effect on this misconception. The other effect might be that the programming models in both frameworks are very similar. In fact, you will find some classes with the same name in both frameworks.

Here is the Deal

Sorry folks but I am going to break the news for you: ASP.NET Web API doesn’t sit on top of ASP.NET MVC. To be more accurate, ASP.NET Web API doesn’t sit on top of anything other than .NET. You can make it sit pretty much on top of wherever the hell you want for it to sit. This is the concept which makes it so darn easy to self-host ASP.NET Web API. The team made this awesome framework sit on top of ASP.NET and WCF by providing two hosting options right out of the box.

Let's make something more clrear because I don't wanna give the wrong impression here. ASP.NET MVC and ASP.NET Web API runs perfectly side by side. It's just that ASP.NET Web API has nothing to do with ASP.NET MVC.

Ok, you wouldn't want to believe a random dude on the internet, would you? Let’s dig a little deeper to see whether I am fabricating here or not.

Prove it!

Let’s open up the ASP.NET Web Stack source code in Visual studio and have a look at the reference list of System.Web.Http project:

10-20-2012 2-24-47 PM

System.Web.Http.dll is the core assembly which holds the logic and everything related to ASP.NET Web API. When you look at the References tab in the above picture, can you see any System.Web.Mvc reference there? No (unless you are hallucinating)! Actually, take a closer look again. Can you now even see any System.Web reference there? No (unless you are hallucinating)! This is because the fact that ASP.NET Web API core infrastructure has been decoupled from the hosting layer.

The below picture shows the assembly references of the ASP.NET hosting project for Web API:

10-20-2012 2-07-18 PM

You can see that System.Web is now referenced here, but can you see any System.Web.Mvc reference here? No (unless you are hallucinating)! So, I am very curious here about where they have gotten the idea that ASP.NET Web API runs on top of ASP.NET MVC because it simply does not!

Let’s now dig a little deeper to see how ASP.NET hosting has been implemented and this will give us a better understanding. ASP.NET Web API plays by the rules and registers itself into the ASP.NET pipeline just like ASP.NET MVC does: with IRouteHandler and IHttpHandler (actually IHttpAsyncHandler) implementations:

10-20-2012 2-13-07 PM

In my personal opinion, the ASP.NET Web API has been designed so beautifully. All the stuff that the hosting layer needs to do is to construct a new HttpConfiguration object and pass that configuration on to HttpServer instance and BOM! You can then invoke that HttpServer instance with HttpMessageInvoker (or anything else which will do the job) and you are now inside the ASP.NET Web API pipeline. This is what HttpControllerHandler is actually doing in an ASP.NET hosting scenario. It gets the HttpContextBase and converts it into an HttpRequestMessage instance. Later, it uses that newly created HttpRequestMessage to invoke the SendAsync method of the HttpMessageInvoker.

This type of design also allows us to write beautiful and easy integration tests against our ASP.NET Web API application. You can find more information about ASP.NET Web API integration testing on Filip’s blog post.

I am now hoping that this will give you a better idea how ASP.NET Web API has been structured and where it really sits on Smile

Pro ASP.NET Web API Book is Available on Amazon for Pre-order

Two days ago, I blogged about the availability of the Pro ASP.NET Web API Book through Apress Alpha Program. Today, the Pro ASP.NET Web API book is now available on Amazon for pre-order
2012-10-15 12:38
Tugberk Ugurlu


Two days ago, I blogged about the availability of the Pro ASP.NET Web API Book through Apress Alpha Program. It was a very valuable blog post for me because this is my first book. Today, I can tell you that you can pre-order Pro ASP.NET Web API book on Amazon and it will be delivered to you when it is available.

In this post, I would like to also give you some information about the book that we are writing. Pro ASP.NET Web API will guide you how to build flexible, extensible web services that run seamlessly on a range of operating systems and devices, from desktops to tablets to smart phones.

We also plan the book to consist of mainly three parts. In Part I, you'll get up to speed on Web API's modern HTTP programming model, asynchronous programming in .NET framework and basic HTTP information. Part II takes you through building a real application so you can see straight away how to put this new technology into practice. The second half of the book features dedicated chapters on topics like routing, controllers, validation and tracing, and we will have chapters on performance, security and an all-important look at unit testing to help you prepare your application for the real world.

ASP.NET Web API makes HTTP a first-class citizen of .NET. With Pro ASP.NET Web API, you will learn how to build HTTP-based web services for your company or business, expose your data to the world across different formats and devices and gain the best possible global reach for your application.

We have still a few chapters to complete but we work hard to get it done as soon as possible. I hope you will enjoy the book Smile

Pro ASP.NET Web API Book is Available Through Apress Alpha Program

I am proud to announce that the Pro ASP.NET Web API book is available through Apress Alpha Program and you can get access to the early bits and completed chapters now.
2012-10-13 10:45
Tugberk Ugurlu


Since April 2012, me and Alexander Zeitler have been working on a book for ASP.NET Web API which is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. Today, all of our efforts have come to fruition and I am proud to announce that the Pro ASP.NET Web API book is available through Apress Alpha Program.

I believe that we are producing an incredibly useful resource which any developer, who wants to leverage the ASP.NET Web API framework, needs under her/his hand. We aimed to avoid explaining and extracting implementation details of the framework as much as possible. Instead, we try to give more examples and use-cases for each component of the framework. There is also going to be a sample application walkthrough.

If you don’t know what The Apress Alpha Program is, here is a little quote from Apress web site:

The Alpha Book Program

Want to get an early look at our titles? Try an Alpha Book! An Alpha Book is a pre-release, still-in-development version of an Apress title. When you purchase an Alpha Book, you get the opportunity to review its content as it advances through the production process. Alpha Book files are updated on a regular basis in your account as new material is completed, all the way through final publication.

Lots of valuable people put her/his effort on this book, especially the acquisitions editor Gwenan Spearing, coordinating editor Anamika Panchoo, development editor Chris Nelson, technical reviewer Robert Swafford, copy editor Tom McCarthy. I would like to thank all of them and the others who made it possible to produce this high quality resource.

We have still a few chapters to complete but we would love to get feedback for the currently available pieces. Go and participate the alpha program and get access to the early bits and completed chapters of the Pro ASP.NET Web API book. Don’t hesitate to reach out to me in any way to give feedback :)

Complex Type Action Parameters with ComplexTypeAwareActionSelector in ASP.NET Web API - Part 2

In this post, we will see how ComplexTypeAwareActionSelector behaves under the covers to involve complex type action parameters during the action selection process.
2012-10-08 06:03
Tugberk Ugurlu


In my previous post on complex type action parameters with ComplexTypeAwareActionSelector in ASP.NET Web API, I showed how to leverage the ComplexTypeAwareActionSelector from WebAPIDoodle project to involve complex type action parameters during the action selection process. In this post, we will go into details to see how ComplexTypeAwareActionSelector behaves under the covers.

Assuming that we have a Person class as below:

public class Person {

    public int FooBar;

    public Nullable<int> Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
        
    public string FullName { 

        get {
            return string.Format("{0} {1}", Name, Surname);
        }
    }

    [BindingInfo(NoBinding = true)]
    public string FullName2 { get; set; }

    public Country Country { get; set; }

    internal int Foo { get; set; }

    public bool IsLegitPerson() {

        return Name.Equals("tugberk", StringComparison.OrdinalIgnoreCase);
    }
}

public class Country {

    public int Id { get; set; }
    public string Name { get; set; }
    public string ISOCode { get; set; }
}

In a real world scenario, we wouldn't use the Person class to bind its values from the URI but bare with me for sake of this demo. Person class has five publicly-settable properties: Id, Name, Surname, FullName2 and Country. It also has internally-settable property called Foo. There are also one read-only property (FullName) and one public field (FooBar). Besides those, the FullName2 property has been marked with WebAPIDoodle.BindingInfoAttribute by setting its NoBinding property to true.

Let’s also assume that we have the below controller and action.

public class FooBarController : ApiController {

    public IEnumerable<FooBar> Get([FromUri]Person person) { 

        //...
    }
}

Now, the question is how ComplexTypeAwareActionSelector behaves here and which members of the Person class are going to be involved to perform the action selection. To perform this logic, the ComplexTypeAwareActionSelector uses two helper methods as below:

internal static class TypeHelper {

    internal static bool IsSimpleType(Type type) {

        return type.IsPrimitive ||
                type.Equals(typeof(string)) ||
                type.Equals(typeof(DateTime)) ||
                type.Equals(typeof(Decimal)) ||
                type.Equals(typeof(Guid)) ||
                type.Equals(typeof(DateTimeOffset)) ||
                type.Equals(typeof(TimeSpan));
    }

    internal static bool IsSimpleUnderlyingType(Type type) {

        Type underlyingType = Nullable.GetUnderlyingType(type);
        if (underlyingType != null) {
            type = underlyingType;
        }

        return TypeHelper.IsSimpleType(type);
    }
}

These two methods belong to ASP.NET Web API source code but they are internal. So, I ported them to my project as they are. As you can see, IsSimpleType method accepts a Type parameter and determines if the type is a simple or primitive type. The IsSimpleUnderlyingType method, on the other hand, looks if the Type is Nullable type. If so, it looks at the underlying type to see if it is a simple type or not. This is how the ComplexTypeAwareActionSelector determines if a parameter is simple type or not.

When the ComplexTypeAwareActionSelector sees a complex type action parameter, it hands that type to another private method to get the useable properties. To mimic how that private helper method filters the properties, I created the a little console application which holds the actual filter logic.

class Program {

    static void Main(string[] args) {

        Console.Write(Environment.NewLine);
        Console.WriteLine("===============================================");
        Console.WriteLine("========This is the actual logic in use========");
        Console.WriteLine("===============================================");

        var propInfos = from propInfo in typeof(Person).GetProperties()
                        where TypeHelper
                              .IsSimpleUnderlyingType(propInfo.PropertyType) && 
                              propInfo.GetSetMethod(false) != null
                              
                        let noBindingAttr = propInfo
                            .GetCustomAttributes().FirstOrDefault(attr => 
                                attr.GetType() == typeof(BindingInfoAttribute)) 
                                    as BindingInfoAttribute
                                    
                        where (noBindingAttr != null) 
                              ? noBindingAttr.NoBinding == false 
                              : true
                              
                        select propInfo;

        foreach (var _propInfo in propInfos) {

            Console.WriteLine(_propInfo.Name);
        }

        Console.ReadLine();
    }
}

Here is what it is doing here for the Person type:

  • It first gets all the public properties of the Person class with GetProperties method of the Type class. So, the ForBar field and the Foo property is ignored.
  • Secondly, it looks if the property is simple underlying type and publicly-settable. If any one of them is not applicable, it ignores them. In our case here, the FullName property, which is a read-only property, and the Country property, which is a complex type property, are ignored.
  • As a last step, it looks at the attributes of the each filtered property. If the property is marked with WebAPIDoodle.BindingInfoAttribute and the BindingInfoAttribute’s NoBinding property is set to true, the property gets ignored. In our case here, the FullName2 property will be ignored.

If we run this little console application, we will see the following result:

SNAGHTML12a04389

As a result, the Id, Name and Surname properties will be considered during the action selection. I would like to point out couple of things before finishing up this post:

  • This is a one-time operation per controller action. For example, when we first fire up our ASP.NET Web API application and send a request which is eventually going to correspond to FooBarController, the action selector will look at all the actions under the FooBarController and performs the above logic along with others and cache lots of stuff including the above logic. So, when you hit the FooBarController next time, this process won’t be run and the result will be pulled directly from the cache.
  • The WebAPIDoodle.BindingInfoAttribute lives inside a separate package named as WebAPIDoodle.Meta. The WebAPIDoodle.Meta package contains some runtime components such as Attributes, Interfaces. This assembly has no dependency on ASP.NET Web API so that it would be easy to reference this on Model or Domain Layer projects.

Happy coding and give feedback for this little feature :)

Tags