I just created an ASP.NET MVC 5 Web API project and added an Entity Framework model and other things to make it work with ASP.NET Identity .

Now I need to create a simple authenticated request for the standard method of this API from the WPF Client application.
ASP.NET MVC 5 Web Interface Code
[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 Client Code
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 { } } }
It seems to be connecting to the host and I am getting the correct error. This is normal.
The response status code does not indicate success: 401 (unauthorized).
The main problem I'm not sure how to send username and password using WPF Client ...
(Guys, Iām not asking if I need to encrypt it and use Auth Filter to implement API methods. I will do it for sure later ...)
I heard that I need to send the username and password in the header request ... but I do not know how to do this using HttpClient client = new HttpClient();
Thanks for any hint!
PS I replaced HttpClient with WebClient and used Task ( Failed to authenticate with ASP.NET Web Api service using HttpClient )?
Academy of programmer
source share