更改为错误的凭据后,HttpWebRequest进行身份验证

时间:2019-08-28 19:38:21

标签: c# authentication httpwebrequest

如果我将Web请求上的凭据从错误更改为正确,反之亦然,则返回401或内容。有没有一种方法可以使登录名或会话无效。

我总是使用当前凭据创建一个新的HttpWebrequest。

将KeepAlive设置为false不会改变

private HttpWebRequest CreateWebRequest(string serviceUrl, string method)
        {
            HttpWebRequest endpointRequest =
                (HttpWebRequest)WebRequest.Create(serviceUrl);

            endpointRequest.Method = method;
            endpointRequest.Accept = "application/json;odata=verbose";

            endpointRequest.KeepAlive = false;

            //endpointRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.);
            if (Domain == null)
            {
                NetworkCredential cred = new System.Net.NetworkCredential(Username, Password);
                endpointRequest.Credentials = cred;
            }
            else
            {
                NetworkCredential cred = new System.Net.NetworkCredential(Username, Password, Domain);
                endpointRequest.Credentials = cred;
            }

            return endpointRequest;
        }


public async Task<JArray> GetListItemsAsync(
            string[] fields = null,
            string[] filter = null,
            string[] orderby = null,
            string[] expand = null,
            int rowlimit = 0)
        {
            try
            {
                var param = ParameterString(fields, filter, orderby, expand, rowlimit);

                var api = "/_api/lists/";
                var serviceUrl = $"{ServerUrl}{api}getbytitle('{ListName}')/items";
                if (param != null)
                {
                    serviceUrl += param;
                }

                var endpointRequest = CreateWebRequest(serviceUrl, "GET");

                HttpWebResponse endpointResponse = (HttpWebResponse)await endpointRequest.GetResponseAsync();
                try
     {
                    WebResponse webResponse = await endpointRequest.GetResponseAsync();
....
}

0 个答案:

没有答案