【发布时间】:2014-01-02 19:41:34
【问题描述】:
我刚刚创建了一个 ASP .NET MVC 5 Web API 项目并添加了实体框架模型和其他东西以使其与ASP. NET Identity 一起工作。
现在我需要从 WPF 客户端应用程序中创建一个对该 API 的标准方法的简单身份验证请求。
ASP .NET MVC 5 Web API 代码
[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
// GET api/Account/UserInfo
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UserInfo")]
public UserInfoViewModel GetUserInfo()
{
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
return new UserInfoViewModel
{
UserName = User.Identity.GetUserName(),
HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
};
}
WPF 客户端代码
public partial class MainWindow : Window
{
HttpClient client = new HttpClient();
public MainWindow()
{
InitializeComponent();
client.BaseAddress = new Uri("http://localhost:22678/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json")); // It tells the server to send data in JSON format.
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Test();
}
private async void Test( )
{
try
{
var response = await client.GetAsync("api/Account/UserInfo");
response.EnsureSuccessStatusCode(); // Throw on error code.
var data = await response.Content.ReadAsAsync<UserInfoViewModel>();
}
catch (Newtonsoft.Json.JsonException jEx)
{
// This exception indicates a problem deserializing the request body.
MessageBox.Show(jEx.Message);
}
catch (HttpRequestException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
}
似乎它正在连接到主机,我得到了正确的错误。没关系。
响应状态码不表示成功:401(未授权)。
我不确定如何使用 WPF 客户端发送用户名和密码的主要问题...
(伙计们,我不是在问我是否必须对其进行加密并在 API 方法实现上使用 Auth Filter。我稍后会这样做...)
听说要在请求头中发送用户名和密码……但不知道怎么用HttpClient client = new HttpClient();实现
感谢您提供任何线索!
附:我是否将HttpClient 替换为WebClient 并使用Task (Unable to authenticate to ASP.NET Web Api service with HttpClient)?
【问题讨论】:
标签: c# wpf asp.net-web-api asp.net-mvc-5 dotnet-httpclient