Dev*_*per 8 c# wpf asp.net-web-api dotnet-httpclient asp.net-mvc-5
我刚刚创建了一个ASP .NET MVC 5 Web API项目,并添加了实体框架模型和其他东西,以使其与ASP一起使用.NET身份.
现在,我需要从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
};
}
Run Code Online (Sandbox Code Playgroud)
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
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
它似乎正在连接到主机,我收到了正确的错误.那没问题.
响应状态代码不表示成功:401(未授权).
我不知道如何使用WPF客户端发送用户名和密码的主要问题...
(伙计们,我不是在问我是否必须加密它并使用Auth Filter而不是API方法实现.我会在以后确实这样做......)
我听说我必须在标头请求中发送用户名和密码...但我不知道如何通过使用来完成 HttpClient client = new HttpClient();
谢谢你的任何线索!
PS我有没有替换HttpClient
用WebClient
和使用Task
(无法进行身份验证的ASP.NET Web API服务与HttpClient的)?
您可以像这样发送当前登录的用户:
var handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
_httpClient = new HttpClient(handler);
Run Code Online (Sandbox Code Playgroud)
然后您可以创建自己的授权过滤器
public class MyAPIAuthorizationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//perform check here, perhaps against AD group, or check a roles based db?
if(success)
{
base.OnActionExecuting(actionContext);
}
else
{
var msg = string.Format("User {0} attempted to use {1} but is not a member of the AD group.", id, actionContext.Request.Method);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent(msg),
ReasonPhrase = msg
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在控制器中要保护的每个操作上使用[MyAPIAuthorizationFilter].
归档时间: |
|
查看次数: |
7079 次 |
最近记录: |