public static string GetResponseContentType(this IRequest httpReq)
{
var specifiedContentType = GetQueryStringContentType(httpReq);
if (!IsNullOrEmpty(specifiedContentType)) return specifiedContentType;
var acceptContentTypes = httpReq.AcceptTypes;
var defaultContentType = httpReq.ContentType;
if (httpReq.HasAnyOfContentTypes(MimeTypes.FormUrlEncoded, MimeTypes.MultiPartFormData))
{
defaultContentType = HostContext.Config.DefaultContentType;
}
var customContentTypes = HostContext.ContentTypes.ContentTypeFormats.Values;
var preferredContentTypes = HostContext.Config.PreferredContentTypesArray;
var acceptsAnything = false;
var hasDefaultContentType = !IsNullOrEmpty(defaultContentType);
if (acceptContentTypes != null)
{
var hasPreferredContentTypes = new bool[preferredContentTypes.Length];
foreach (var acceptsType in acceptContentTypes)
{
var contentType = ContentFormat.GetRealContentType(acceptsType);
acceptsAnything = acceptsAnything || contentType == "*/*";
for (var i = 0; i < preferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) continue;
var preferredContentType = preferredContentTypes[i];
hasPreferredContentTypes[i] = contentType.StartsWith(preferredContentType);
//Prefer Request.ContentType if it is also a preferredContentType
if (hasPreferredContentTypes[i] && preferredContentType == defaultContentType)
return preferredContentType;
}
}
for (var i = 0; i < preferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) return preferredContentTypes[i];
}
if (acceptsAnything)
{
if (hasDefaultContentType)
return defaultContentType;
if (HostContext.Config.DefaultContentType != null)
return HostContext.Config.DefaultContentType;
}
foreach (var contentType in acceptContentTypes)
{
foreach (var customContentType in customContentTypes)
{
if (contentType.StartsWith(customContentType, StringComparison.OrdinalIgnoreCase))
return customContentType;
}
}
}
if (httpReq.ContentType.MatchesContentType(MimeTypes.Soap12))
{
return MimeTypes.Soap12;
}
if (acceptContentTypes == null && httpReq.ContentType == MimeTypes.Soap11)
{
return MimeTypes.Soap11;
}
//We could also send a '406 Not Acceptable', but this is allowed also
return HostContext.Config.DefaultContentType;
}