Wcf web api WCF API和API密钥授权

Wcf web api WCF API和API密钥授权,wcf-web-api,api-key,Wcf Web Api,Api Key,在WCF中编写或开始编写WEB API rest服务。一切都相对顺利。然而,我遇到了一个小问题。我已经实现了这一点 用于密钥验证。(我不确定这是否是WCF WEB API的正确方法,因为它看起来更像rest服务实现) 不管怎样,它似乎起作用了。但是,如果未提供api密钥,则浏览器中不会显示异常。也就是说,如果我提供密钥,它会正确返回,如果我不提供,它只会显示一个空白页 private static void CreateErrorReply(OperationContext operati

在WCF中编写或开始编写WEB API rest服务。一切都相对顺利。然而,我遇到了一个小问题。我已经实现了这一点

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

不管怎样,它似乎起作用了。但是,如果未提供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;

            }
        }
    }
private static void CreateErrorReply(OperationContext OperationContext,字符串键)
{
//错误消息被填充,以便IE在默认情况下显示响应
使用(var sr=newstringreader(“+apErrorHTML))
{
XElement响应=XElement.荷载(sr);
使用(Message reply=Message.CreateMessage(MessageVersion.None,null,response))
{
HttpResponseMessageProperty responseProp=new HttpResponseMessageProperty(){StatusCode=HttpStatusCode.Unauthorized,StatusDescription=String.Format(“{0}”是无效的API密钥,密钥)};
responseProp.Headers[HttpResponseHeader.ContentType]=“text/html”;
reply.Properties[HttpResponseMessageProperty.Name]=ResponsePro;
operationContext.RequestContext.Reply(Reply);
//将请求上下文设置为null以终止此请求的处理
operationContext.RequestContext=null;
}
}
}

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

您使用的是WCF还是WCF Web API?如果是后者,那么您可以下载包含API密钥验证示例(在扩展Web API管道的.chm文件中-消息处理程序-示例:检查API密钥)嗨,Tony-我已经看过了,这意味着要更改方法。我相信这会很有效果,但我仍在琢磨原始代码失败的原因。@philbird嗨,philbird,我正在使用与您相同的方法。你发现了什么导致空白响应而不是返回无效的API密钥/令牌吗?你使用WCF还是WCF Web API?如果是后者,那么您可以下载包含API密钥验证示例(在扩展Web API管道的.chm文件中-消息处理程序-示例:检查API密钥)嗨,Tony-我已经看过了,这意味着要更改方法。我相信这会很有效果,但我仍在琢磨原始代码失败的原因。@philbird嗨,philbird,我正在使用与您相同的方法。你发现了什么导致空白响应而不是返回无效的API密钥/令牌吗?