Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class HeaderControllerSelector : DefaultHttpControllerSelector
- {
- public HeaderControllerSelector(HttpConfiguration configuration) : base(configuration)
- {
- }
- public override string GetControllerName(HttpRequestMessage request)
- {
- string controllerName = base.GetControllerName(request);
- if (!request.Headers.Contains("Accept"))
- return controllerName;
- IEnumerable<string> acceptHeaders = request.Headers.GetValues("Accept");
- string headerValue = GetVertionFromHeaders(acceptHeaders);
- if (string.IsNullOrWhiteSpace(headerValue) || headerValue == "1")
- {
- return controllerName;
- }
- int controllerVersion;
- if (!int.TryParse(headerValue, out controllerVersion))
- {
- return controllerName;
- }
- controllerName = string.Format("{0}v{1}", controllerName, controllerVersion);
- HttpControllerDescriptor controllerDesc = null;
- bool isVersionFound = GetControllerMapping().TryGetValue(controllerName, out controllerDesc);
- if (!isVersionFound)
- {
- string message = "No HTTP resource was found for specified request URI {0} and version {1}";
- throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format(message, request.RequestUri, controllerVersion)));
- }
- return controllerName;
- }
- private static string GetVertionFromHeaders(IEnumerable<string> acceptHeaders)
- {
- foreach (string header in acceptHeaders)
- {
- string[] sk = header.Split(';');
- foreach (string acceptDef in sk)
- {
- string[] def = acceptDef.Trim().Split('=');
- if (def.Length == 2 && def[0] == "version")
- {
- return def[1];
- }
- }
- }
- return string.Empty;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment