DelegatingHandler for API Key Verification issue in Preview 5

Topics: Web Api
Sep 27, 2011 at 10:48 AM

Hi,

After updating to preview 5, I started getting error "Invalid handler provided: 'ApiKeyVerificationChannel'. It must inherit from base type 'DelegatingHandler', cannot be abstract, and must expose a default public constructor.<br>Parameter name: handlers[0]" in my API Key verification channel.

It worked fine in preview 4. I have changed it as per "breaking changes" list(Basically replaced Channel by Handler).

Below is the class. What's wrong?

 public class ApiKeyVerificationChannel : DelegatingHandler
    {
        public const string KeyHeaderName = "X-AuthKey";
        IKeyVerifier keyVerifier;

        public ApiKeyVerificationChannel(HttpMessageHandler innerChannel)
            : this(innerChannel, new KeyVerifier())
        {

        }
        public ApiKeyVerificationChannel(HttpMessageHandler innerChannel, IKeyVerifier keyVerifier)
            : base(innerChannel)
        {
            this.keyVerifier = keyVerifier;
        }    
       
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                IEnumerable<string> values = null;
               
                if (request.Headers.TryGetValues(KeyHeaderName, out values))
                {
                    var key = values.First();
                    if (this.keyVerifier.Verify(key))
                    {
                        return base.SendAsync(request, cancellationToken);
                    }
                }
                return Task.Factory.StartNew(() =>
                {
                    var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                    response.Content=new StringContent("You need to provide a valid key for consume these Apis");
                    return response;
                });
            }

            catch (Exception ex)
            {
               
            }
          
        }
    }

Sep 27, 2011 at 3:09 PM

You need a constructor that does not require parameters.  Add this to your class:

public ApiKeyVerificationChannel() {  }     

Oct 29, 2011 at 11:28 AM

IKeyVerifier is part of which dll and namespace. I can not resolve this interface and keyVerifier class instance. I used webapi nugget for adding the references.

Oct 29, 2011 at 2:19 PM

Pretty sure IKeyVerifier is your own logic.  In this example you'd inject IKeyVerifier that supported a Verify() method to return true if the key was valid.  Substitute your own key verification logic there.  You may or may not use IKeyVerifier based on what makes sense in your own key verification logic.