我刚刚创建了一个ASP .NET MVC 5 Web API项目并添加了实体框架模型和其他东西以使其能够使用ASP。网络身份 http://identity.codeplex.com/.
现在,我需要从 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
with WebClient
并使用Task
(无法使用 HttpClient 对 ASP.NET Web Api 服务进行身份验证 https://stackoverflow.com/questions/10308938/unable-to-authenticate-to-asp-net-web-api-service-with-httpclient)?