使用MVC 4访问DelegatingHandler中的路由数据

时间:2013-06-06 23:47:47

标签: asp.net asp.net-mvc asp.net-web-api

我现在只是注册这些路由如何在WebApiKeyHandler.cs中获取Apikey值,因为它不是查询字符串的一部分所以我得到null。还指导我如何验证密钥是Web Api项目的最佳实践?

public static void Register(HttpConfiguration config)
        {
           config.Routes.MapHttpRoute(
           name: "DefaultApi2",
           routeTemplate: "api/v1/users/{apikey}/{controller}/{action}/",
           defaults: new { id = RouteParameter.Optional }
                );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/v1/users/{apikey}/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.MessageHandlers.Add(new WebApiKeyHandler());  // global message handler
        }

WebApiKeyHandler.cs

   public class WebApiKeyHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string apikey = HttpUtility.ParseQueryString(request.RequestUri.Query).Get(Constants.API_KEY_QUERY_STRING);
            if (string.IsNullOrWhiteSpace(apikey))
            {
                HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.Forbidden, ErrorCodes.API_KEY_EMPTY_ERROR);
                var tsc = new TaskCompletionSource<HttpResponseMessage>();
                tsc.SetResult(response);
                return tsc.Task;
            }
            else if (!ValidateKey(apikey))
            {
                HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.Forbidden, ErrorCodes.API_KEY_INVALID_ERROR);
                var tsc = new TaskCompletionSource<HttpResponseMessage>();
                tsc.SetResult(response);
                return tsc.Task;
            }
            else
            {
                return base.SendAsync(request, cancellationToken);
            }
        }

        private static bool ValidateKey(string apiKey)
        {
            Guid key;
            Guid.TryParse(apiKey, out key);
            return new StAccountsDomainContext().ApiSubscriptions.Any(x => x.ApiKey == key && x.IsActive == true && !x.ApiIBlacklists.Any());
        }

        private static bool ValidateSecretKey(string apiKey, string secretKey)
        {
            Guid key1;
            Guid.TryParse(apiKey, out key1);

            Guid key2;
            Guid.TryParse(secretKey, out key2);

            return new StAccountsDomainContext().ApiSubscriptions.Any(x => x.ApiKey == key1
                                                                        && x.SecretKey == key2
                                                                        && x.IsActive == true
                                                                        && !x.ApiIBlacklists.Any());
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用HttpRequestMessage上的GetRouteData()扩展名来获取路由数据。示例:request.GetRouteData().Values