With ASP.NET Web API it’s now easier than ever to create lightweight HTTP services in .NET. Out of the box the ApiControllers you implement can read json, xml and form encoded values from the HTTP request but also write xml and json to the HTTP response.
HTTP has the concept of content negotiation. This means that when a client requests a resource, it can tell the server that it wants the result in a specific format.
Below you can see an HTTP request that requests json:
And in the HTTP response the data is formatted accordingly:
If the client requests the response to be formatted as xml:
Then the result will be returned as xml:
This mechanism can be extended to support different kind of formatters to read from or write to the body of a request or response.
Let’s say we want to support an additional format that can write appointments in iCal format. To create a custom formatter you inherit from BufferedMediaTypeFormatter or MediaTypeFormatter. For this example I chose the first one.
The code is pretty straightforward and represents a very simple implementation of the iCal standard. The only WebAPI specific code can be found in the constructor.There we add the mapping for the headers we want the formatter to be invoked for. After we add the formatter to the configuration object, it will be invoked automatically whenever a client says it accepts “text/iCal”.
Unfortunately Outlook does not send an accept header with text/iCal when it requests resources from an internet calendar. So we need to work around this problem.
Here another extensibility point of ASP.NET Web API comes into play: MessageHandlers.
MessageHandlers allow you to plug into the request processing pipeline on its lowest level. You can inspect the request and response message and make changes. In this case we can inspect the user agent that is added to the request when Outlook contacts our service. When we find a match, we will add an additional header to the incoming request.
We also add this message handler to the configuration object.
We now have everything in place to add an internet calendar in Outlook and view the appointments in our WebAPI.
- Open Outlook
- Go to Calendar
- In the ribbon, click on “Open Calendar” and then “From Internet”
- Fill in the url of the AppointmentService in WebAPI i.e. http://localhost:58250/api/appointments
- Click Ok.
You now have one AppointmentController serving json, xml and iCal! The complete source can be downloaded here.
4 Replies to “Exposing iCal data in WebAPI”
Your blog is very simple and clear to understand and follow. I followed your blog and made it work.
Now i want to add webcal:// prefix to my api url and allow user to click directly on a link to automatically open outlook and import events, but i failed in making it work, outlook is opened but no event is imported.
You have any idea about it? Would be great to hear from you.
Sorry I don’t know the answer. Have you checked if a request is made using fiddler or something?