Skip to content

DmitryFillo/AspNet.WebApi.CookiesPassthrough

Repository files navigation

ASP.NET Web API CookiesPassthrough

image

Allows you to add cookies for IHttpActionResult in WebAPI controllers.

Motivation

There are several ways to add cookies to the response in WebAPI. The recommended way, according to the docs, is to use resp.Headers.AddCookies(cookies) extension method, but there are some disadvantages:

  • Cookie values are always encoded. It's complicated topic, so encode / decode should be configurable, e.g. Chrome works well with spaces in cookie values or sometimes you need = char in a cookie value.
  • CookieHeaderValue supports name-value pairs and such collections will be presented as cookie-name=key1=value1&key2=value2, but collection will be encoded if you'll try to set it via just passing string. Passing cookie collection strings directly is useful for cases when you passing cookie values through services, e.g. integration with legacy cookie-based APIs.

Another way is to set cookies on HttpResponse.Cookies via HttpContext (check example), but there are even more serious disadvantages:

  • Using HttpContext in WebAPI is bad practice, because you cannot get them in self host.
  • Potential problems with new Thread().
  • Harder to mock.
  • Complicated behaviour.

Better to have simple API for IHttpActionResult w/o described disadvantages. Also good to have localhost support or "enable these cookies for all subdomains" feature out-the-box.

How to use

You can install AspNet.WebApi.CookiesPassthrough package via nuget.

You can enable cookies for all subdomains:

If domain is localhost

Browsers has problems with localhost cookies. If you'll specify domain as localhost or even .localhost it will not be added to the response at all to make cookies with localhost work for almost all browsers.

Enable cookies for all subdomains

When you call .EnableCookiesForAllSubdomains() or use .AddCookiesForAllSubdomains(...) the following domain convertion will be applied:

Play with examples

Check AspNet.WebApi.CookiesPassthrough.Example project.

Special thanks to

  • Thanks to rustboyar and niksanla2. These guys faced some issues with cookies (related with encoding) in WebAPI when trying to send them back from legacy API and developed PoC. I decided to research the topic a bit and create this package to make common "cookiejob" simple.
  • Thanks to KatArt for nuget package cute icon (love this telegram stickers impression).