WCF API和API密钥授权

时间:2012-01-02 17:10:02

标签: wcf-web-api api-key

编写或开始在WCF中编写WEB API rest服务。一切都相当顺利。但是,我遇到了一个小问题。我实现了这个;

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

用于密钥验证。 (我不确定这是否是WCF WEB API的正确方法,因为它看起来更像是其他服务实现)。

无论如何,它似乎有效。但是,如果未提供api密钥,则浏览器中不会显示异常。即如果我提供密钥,它会正确返回,如果我没有,它只显示一个空白页面。

  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;

            }
        }
    }

而不是显示错误,结果是空白响应。有人可以帮忙吗?

0 个答案:

没有答案