Here's my custom formatter which I want to use for "application/x.product" content type:
public class ProductFormatter : MediaTypeFormatter
{
public ProductFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/x.product"));
}
public override bool CanReadType(Type type)
{
return false;
}
public override bool CanWriteType(Type type)
{
var result = (type == typeof(Product) || type == typeof(IEnumerable<Product>));
return result;
}
public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
List<string> productStrings = new List<string>();
IEnumerable<Product> products = value is Product ? new Product[] { (Product)value } : (IEnumerable<Product>)value;
foreach (Product product in products)
{
productStrings.Add(string.Format("{0},{1},{2}",
product.ProductID, product.Name, product.Price));
}
StreamWriter writer = new StreamWriter(writeStream);
await writer.WriteAsync(string.Join(",", productStrings));
writer.Flush();
}
}
Registered as:
config.Formatters.Add(new ProductFormatter());
I also have a custom negotiator (also registered):
public class CustomNegotiator : DefaultContentNegotiator
{
public override ContentNegotiationResult Negotiate(Type type,
HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
// look for an appropriate formatter
MediaTypeFormatter formatter = null;
foreach(var f in formatters)
{
var mediaType = f.SupportedMediaTypes.Where(mt => mt.MediaType == "application/x.product").SingleOrDefault();
if (mediaType != null)
{
formatter = f;
break;
}
}
if (request.Headers.UserAgent.Where(x => x.Product != null
&& x.Product.Name.ToLower().Equals("chrome")).Count() > 0 && formatter != null)
{
// if client is chrome then return superproduct and use custom formatter for it
return new ContentNegotiationResult(formatter,
new MediaTypeHeaderValue("application/x.product")
);
}
else
{
return base.Negotiate(type, request, formatters);
}
}
}
I also want to use this with application/x.product when a client is Google Chrome.
Is my way of searching an appropriate formatter okay, or is there a better way?