2

Written or started to write a WEB API rest service in WCF. It's all going relatively well. However, I've come across a small problem. I've implemented this;

http://blogs.msdn.com/b/rjacobs/archive/2010/06/14/how-to-do-api-key-verification-for-rest-services-in-net-4.aspx

For key validation. (I'm not sure if this is the correct approach for WCF WEB API, since it looks more like the rest service implementation).

Anyway, it seems to work. However, when the api key is not provided the exception is not been displayed in the browser. I.e. if I provide the key, it returns correctly, if I don't it just shows a blank page.

  private static void CreateErrorReply(OperationContext operationContext, string key)
    {
        // The error message is padded so that IE shows the response by default
        using (var sr = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + APIErrorHTML))
        {
            XElement response = XElement.Load(sr);
            using (Message reply = Message.CreateMessage(MessageVersion.None, null, response))
            {

                HttpResponseMessageProperty responseProp = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized, StatusDescription = String.Format("'{0}' is an invalid API key", key) };
                responseProp.Headers[HttpResponseHeader.ContentType] = "text/html";
                reply.Properties[HttpResponseMessageProperty.Name] = responseProp;
                operationContext.RequestContext.Reply(reply);
                // set the request context to null to terminate processing of this request
                operationContext.RequestContext = null;

            }
        }
    }

Instead of this showing an error, the result is a blank response. Can anyone help?

hippietrail
  • 15,848
  • 18
  • 99
  • 158
philbird
  • 789
  • 1
  • 8
  • 15
  • Are you using WCF or WCF Web API? If latter then you can download the [documentation](http://wcf.codeplex.com/releases) which contains example of the API key verification (in the .chm file Extending the Web API Pipeline - Message Handlers - Example: Checking for an API key) – Toni Parviainen Jan 02 '12 at 18:17
  • Hi Tony - I've had a look at that and it would mean changing the approach. I'm sure it would be affective, but I'm still scratching my head as to why the original code fails. – philbird Jan 08 '12 at 07:44
  • @philbird Hi philbird, I am using the same approach as you do. Did you find out what caused the blank response instead of returning Invalid API Key / Token? – Maki92 Dec 05 '17 at 04:15

0 Answers0