0

我正在编写一个客户端站点 C# 程序,我想使用 [Authorize] 访问由 ApiController 实现的 Web 服务。

服务器端代码如下:

[Authorize]
public class EventsController : ApiController
{
    [ActionName("Default")]
    [HttpGet]
    public EventLog[] Get([FromUri]EventsFilter filter)
    {
        return this.HandleExceptions(() => EventService.GetEvents(filter));
    }
}

如何编写客户端 C# 代码来访问它?

4

1 回答 1

0

我已经通过使用博客中的方法解决了这个问题:http: //soabubblog.wordpress.com/2013/07/10/web-api-httpclient-authentication/

以下帮助方法用于登录服务。

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";
  }
}
于 2014-02-04T05:47:30.387 回答