【问题标题】:Configure authentication for http requests from web.config file从 web.config 文件为 http 请求配置身份验证
【发布时间】:2016-03-04 12:26:31
【问题描述】:

所以我需要从 c# 到 web api 执行大量请求,并且它们需要基本身份验证。我知道我可以这样做:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");

        String username = "abc";
        String password = "123";
        String encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
        httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

但我不想手动将凭据添加到每个请求的标头中。我想知道是否有一种方法可以全局验证我的所有请求(来自 web.config,可能类似于用于 sql 连接的 connectionStrings?)。

【问题讨论】:

  • 您可以随时添加全局过滤器,或者在您需要添加的任何特定方法上方手动添加

标签: c# asp.net httprequest


【解决方案1】:

您可以创建一个继承 HttpClient 的类,并按照您的建议从 web.config 获取用户名和密码

public class AuthenticatedClient : HttpClient
{
    public AuthenticatedClient()
    {
        string password = ConfigurationManager.AppSettings["Password"];
        string userName = ConfigurationManager.AppSettings["UserName"];
        string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + password));

        BaseAddress = new Uri("http://url");
        DefaultRequestHeaders.Add("Authorization", "Basic " + encoded);
        DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }
}

在 web.config 中

<appSettings>
    <add key="UserName" value="abc" />
    <add key="Password" value="123" />
</appSettings>

然后无论您想在哪里发出请求,都可以像标准的 HttpClient 一样使用它

StringContent stringContent = new StringContent("json request string", UnicodeEncoding.UTF8, "application/json");

using (var client = new AuthenticatedClient())
{
   HttpResponseMessage response = await client.PostAsync("/api/whatever", stringContent);
}

【讨论】:

  • 不完全是我想要的,但仍然是一个有趣的解决方案。谢谢!
【解决方案2】:

如果您希望您的凭据是静态的但可以更改,那么您可以继续您的想法并将用户名和密码添加到 web.config 应用程序设置。请参考this

您可以创建一个实用方法来添加授权标头。

public static void AddAuthorizationHeader(ref HttpWebRequest request)
{
    string username = //load value from web.config
    string password = //load value from web.config
    string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
}

因此,只需将它用于所有需要该标头的 http Web 请求..

HttpWebRequest request = new HttpWebRequest();
UtilityClass.AddAuthorizationHeader(ref request);
request.ContentType = "application/json";
request.Method = "POST";

附:我正在使用我的手机,很抱歉这个糟糕的答案。但我想这就是你需要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多