2

在 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;

            }
        }
    }

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

4

0 回答 0