SanSYS

HeaderControllerSelector

Oct 1st, 2015
24,220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. public class HeaderControllerSelector : DefaultHttpControllerSelector
  2. {
  3.     public HeaderControllerSelector(HttpConfiguration configuration) : base(configuration)
  4.     {
  5.     }
  6.  
  7.     public override string GetControllerName(HttpRequestMessage request)
  8.     {
  9.         string controllerName = base.GetControllerName(request);
  10.  
  11.         if (!request.Headers.Contains("Accept"))
  12.             return controllerName;
  13.  
  14.         IEnumerable<string> acceptHeaders = request.Headers.GetValues("Accept");
  15.  
  16.         string headerValue = GetVertionFromHeaders(acceptHeaders);
  17.  
  18.         if (string.IsNullOrWhiteSpace(headerValue) || headerValue == "1")
  19.         {
  20.             return controllerName;
  21.         }
  22.  
  23.         int controllerVersion;
  24.  
  25.         if (!int.TryParse(headerValue, out controllerVersion))
  26.         {
  27.             return controllerName;
  28.         }
  29.  
  30.         controllerName = string.Format("{0}v{1}", controllerName, controllerVersion);
  31.  
  32.         HttpControllerDescriptor controllerDesc = null;
  33.  
  34.         bool isVersionFound = GetControllerMapping().TryGetValue(controllerName, out controllerDesc);
  35.  
  36.         if (!isVersionFound)
  37.         {
  38.             string message = "No HTTP resource was found for specified request URI {0} and version {1}";
  39.  
  40.             throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format(message, request.RequestUri, controllerVersion)));
  41.         }
  42.  
  43.         return controllerName;
  44.     }
  45.  
  46.     private static string GetVertionFromHeaders(IEnumerable<string> acceptHeaders)
  47.     {
  48.         foreach (string header in acceptHeaders)
  49.         {
  50.             string[] sk = header.Split(';');
  51.  
  52.             foreach (string acceptDef in sk)
  53.             {
  54.                 string[] def = acceptDef.Trim().Split('=');
  55.  
  56.                 if (def.Length == 2 && def[0] == "version")
  57.                 {
  58.                     return def[1];
  59.                 }
  60.             }
  61.         }
  62.  
  63.         return string.Empty;
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment