具有基本身份验证的Webclient / HttpWebRequest返回404找不到有效URL

时间:2013-04-16 18:20:23

标签: c# .net

编辑:我想回过头来注意问题根本不是我的问题,而是在另一方的代码中使用代码。

我正在尝试使用基本身份验证来启动页面。我一直收到404 Page not found错误。我可以将我的网址复制并粘贴到浏览器中并且工作正常(如果我没有登录到他们的网站,它会弹出一个凭据框,否则会打开我想要打开的内容)。我必须到正确的地方并进行身份验证,因为如果我一方面输入了错误的用户名/密码,我得到一个401(未经过身份验证的错误),如果我在查询字符串中传递了一个错误的参数,我会收到内部服务器错误500 。我尝试使用Webclient和HttpWebRequest都导致相同的404未找到错误。

使用Webclient:

string url = "MyValidURLwithQueryString";
WebClient client = new WebClient();
String userName = "myusername";
String passWord = "mypassword";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;
var result = client.DownloadString(url);
Response.Write(result);

使用HttpWebRequest

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("MyValidURL");
string authInfo = "username:password";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Http.Get;
request.AllowAutoRedirect = true;
request.Proxy = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();
Response.Write(s);

4 个答案:

答案 0 :(得分:78)

//BEWARE
//This works ONLY if the server returns 401 first
//The client DOES NOT send credentials on first request
//ONLY after a 401
client.Credentials = new NetworkCredential(userName, passWord); //doesnt work

//So use THIS instead to send credentials RIGHT AWAY
string credentials = Convert.ToBase64String(
    Encoding.ASCII.GetBytes(userName + ":" + password));
client.Headers[HttpRequestHeader.Authorization] = string.Format(
    "Basic {0}", credentials);

答案 1 :(得分:23)

尝试将Web客户端请求身份验证部分更改为:

NetworkCredential myCreds = new NetworkCredential(userName, passWord);
client.Credentials = myCreds;

然后打电话,似乎对我来说很好。

答案 2 :(得分:11)

这部分代码对我来说很好:

module ALU_32 (iA, iB ,iCin ,ctrl, oCarry,oZero, out);    
input [31:0] iA,iB;
output [31:0] out;
input iCin,ctrl;
output oCarry,oZero;
reg [31:0] out;
reg oCarry;
reg oZero;
always@ (ctrl)
    begin 
        case(ctrl)
            4'b0: out<=iA&iB;
            4'b0001: out<=iA|iB;
            4'b0010: {oCarry ,out}<=iA+iB;
            4'b0011: out<=iA~|iB;    //error
            4'b0100: 
            begin 
                if(iA==iB)
                    out<=32'b1;
            end  
            4'b0101: out<=iA-iB;  //error
            4'b0110:    //error
            begin 
                if(iA<iB)
                    out<=32'b1;
                else
                    out<=32'b0;
                end
            4'b0111:   out<=iA*iB;     //error
            4'b1000: out<=iA/iB;        //error

        end
       always@(out)
           begin
               if(out==0)
                   oZero<=1;
               end

      endmodule

答案 3 :(得分:2)

如果它在您使用浏览器时工作,然后第一次传递您的用户名和密码 - 那么这意味着一旦身份验证完成,您的浏览器的请求标头将设置为所需的身份验证值,然后传递给每次向托管服务器发出请求时。

首先检查请求标头(这可以使用Web开发人员工具完成),一旦你在标头中建立了所需的内容,你就可以在你的HttpWebRequest标头中传递它。

摘要式身份验证示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace NUI
{
    public class DigestAuthFixer
    {
        private static string _host;
        private static string _user;
        private static string _password;
        private static string _realm;
        private static string _nonce;
        private static string _qop;
        private static string _cnonce;
        private static DateTime _cnonceDate;
        private static int _nc;

public DigestAuthFixer(string host, string user, string password)
{
    // TODO: Complete member initialization
    _host = host;
    _user = user;
    _password = password;
}

private string CalculateMd5Hash(
    string input)
{
    var inputBytes = Encoding.ASCII.GetBytes(input);
    var hash = MD5.Create().ComputeHash(inputBytes);
    var sb = new StringBuilder();
    foreach (var b in hash)
        sb.Append(b.ToString("x2"));
    return sb.ToString();
}

private string GrabHeaderVar(
    string varName,
    string header)
{
    var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
    var matchHeader = regHeader.Match(header);
    if (matchHeader.Success)
        return matchHeader.Groups[1].Value;
    throw new ApplicationException(string.Format("Header {0} not found", varName));
}

private string GetDigestHeader(
    string dir)
{
    _nc = _nc + 1;

    var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
    var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
    var digestResponse =
        CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));

    return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
        "algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
        _user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}

public string GrabResponse(
    string dir)
{
    var url = _host + dir;
    var uri = new Uri(url);

    var request = (HttpWebRequest)WebRequest.Create(uri);

    // If we've got a recent Auth header, re-use it!
    if (!string.IsNullOrEmpty(_cnonce) &&
        DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
    {
        request.Headers.Add("Authorization", GetDigestHeader(dir));
    }

    HttpWebResponse response;
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    }
    catch (WebException ex)
    {
        // Try to fix a 401 exception by adding a Authorization header
        if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
            throw;

        var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
        _realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
        _nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
        _qop = GrabHeaderVar("qop", wwwAuthenticateHeader);

        _nc = 0;
        _cnonce = new Random().Next(123400, 9999999).ToString();
        _cnonceDate = DateTime.Now;

        var request2 = (HttpWebRequest)WebRequest.Create(uri);
        request2.Headers.Add("Authorization", GetDigestHeader(dir));
        response = (HttpWebResponse)request2.GetResponse();
    }
    var reader = new StreamReader(response.GetResponseStream());
    return reader.ReadToEnd();
}

}

然后你可以称之为:

DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);

如果网址为:http://xyz.rss.com/folder/rss则域名为:http://xyz.rss.com(域名部分)目录:/文件夹/ rss(其余网址)

您也可以将其作为流返回并使用XmlDocument Load()方法。