C# 如何使用[Authorize]访问ApiController实现的web服务
我正在编写一个客户端站点C#程序,我想通过[Authorize]访问ApiController实现的web服务 服务器端代码如下所示:C# 如何使用[Authorize]访问ApiController实现的web服务,c#,asp.net,c#-4.0,asp.net-apicontroller,C#,Asp.net,C# 4.0,Asp.net Apicontroller,我正在编写一个客户端站点C#程序,我想通过[Authorize]访问ApiController实现的web服务 服务器端代码如下所示: [Authorize] public class EventsController : ApiController { [ActionName("Default")] [HttpGet] public EventLog[] Get([FromUri]EventsFilter filter) { return thi
[Authorize]
public class EventsController : ApiController
{
[ActionName("Default")]
[HttpGet]
public EventLog[] Get([FromUri]EventsFilter filter)
{
return this.HandleExceptions(() => EventService.GetEvents(filter));
}
}
如何编写客户端C#代码来访问它 我使用博客中的方法解决了这个问题: 以下帮助器方法用于登录到服务
使用誓言来验证对API的访问,这就是所有API访问的处理方式,不应该有状态管理,即使用API的cookie,您的客户端应该请求令牌,然后存储此令牌以通过令牌/秘密握手来验证请求。没有直接的方法从盒子中实现它。但你可以使用一些第三方技术,让你的生活更轻松。举个例子来看
static class AuthenticationService
{
public static HttpClient CreateAuthenticatedSession(out HttpStatusCode statusCode)
{
var Client = new HttpClient
{
BaseAddress = new Uri(@" http://localhost:52310/ ")
};
var Result = Client.PostAsync("/Account/WebLogOn/",
new FormUrlEncodedContent(
new Dictionary<string, string>
{
{"UserName", "test"},
{"Password", "1234"}
}
)
).Result;
//Result.EnsureSuccessStatusCode();
statusCode = Result.StatusCode;
return Client;
}
}
void GetProductList()
{
HttpStatusCode statusCode;
var httpClientSession
= Helpers.AuthenticationService.CreateAuthenticatedSession(out statusCode);
if (statusCode == HttpStatusCode.OK)
{
httpClientSession.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = httpClientSession.GetAsync("/api/product").Result;
// Result.EnsureSuccessStatusCode();
if (result.StatusCode == HttpStatusCode.OK)
{
string responseText = result.Content.ReadAsStringAsync().Result;
}
else
{
string errorText = string.Format("[{0}] - Cannot get the product list.", result.StatusCode);
}
}
else
{
string errorText1 = "Authentication Failed";
}
}