WPF使用基本身份验证对ASP.NET MVC Rest Service进行身份验证

时间:2013-04-06 23:05:52

标签: wpf asp.net-mvc rest authentication service

我正在使用一个使用ASP.NET MVC(Restful Behavior)的WPF应用程序。 MVC应用程序使用基本身份验证。那么,如何验证我的WPF应用程序以访问MVC Url?请建议。

由于

1 个答案:

答案 0 :(得分:1)

您可以使用HttpClient

using (var client = new HttpClient())
{
    var username = "john";
    var password = "secret";

    var buffer = Encoding.ASCII.GetBytes(string.Concat(username, ":", password));
    var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));
    client.DefaultRequestHeaders.Authorization = authHeader;
    var task = client.GetAsync("https://example.com/somemethod");
    if (task.Result.StatusCode == HttpStatusCode.Unauthorized)
    {
        Console.WriteLine("wrong credentials");
    }
    else
    {
        task.Result.EnsureSuccessStatusCode();
        Console.WriteLine(task.Result.Content.ReadAsAsync<string>().Result);
    }
}
相关问题