添加 WWW-Authenticate 标头会出现错误

问题描述

我正在尝试在我的 .NET HttpListener 上配置基本访问授权,但我一直遇到同样的错误。我已经尝试了可以​​在本网站和许多其他网站上找到的所有解决方案,但都没有成功。

我需要使用 admin/admin 作为用户名/密码进行基本身份验证。 wikipedi page 显示标题的外观,我遵循了这一点。

我不断收到错误消息“必须使用正确的方法更改标题 WWW-Authenticate,参数:名称”,但是没有必须添加名为“名称”的参数,如维基百科页面所示。不幸的是,我的选择已经用完了,希望有人能提供帮助。

我的代码如下

private void WebRequestCallback(IAsyncResult result)
{
    if (httpListener == null)
    {
        return;
    }

    HttpListenerContext context = httpListener.EndGetContext(result);

    if (basicAccessAuth)
    {
        HttpListenerRequest Request = context.Request;
        HttpListenerResponse Response = context.Response;

        httpListener.AuthenticationSchemes = AuthenticationSchemes.Basic;
        NameValueCollection nvCol = new NameValueCollection();
        nvCol.Add("Authorization","admin:admin");
        httpListener.Realm = "Overflow";

        Request.Headers.Add(nvCol); // error gets thrown here,missing "name" parameter
        Response.Headers.Add("WWW-Authenticate: Basic YWRtaW46YWRtaW4=");

        HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
        MessageBox.Show(identity.Name);
    }

    httpListener.BeginGetContext(new AsyncCallback(WebRequestCallback),httpListener);

    if (ReceiveWebRequest != null)
    {
        ReceiveWebRequest(context);
    }
    ProcessRequest(context);

}

解决方法

我已经设法找出我的问题。我以错误的方式添加了标题,它应该是 Response.AddHeader 而不是 Response.Headers.Add