我正在尝试测试我的Web API
[Test]
public void PolicyController_GetFirstPage_Successful()
{
using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/policies/~/~/0"))
{
using (var response = Client.SendAsync(request, CancellationToken.None).Result)
{
//blah blah
}
}
}
但我的控制器操作有[Authorize]
属性,所以我收到了未经授权的错误。
我该如何处理这个案子?
答案 0 :(得分:2)
首先,您需要获取访问令牌。然后你可以在头文件中发送带有访问令牌的GET请求。您可以在此处详细了解:http://msdn.microsoft.com/en-us/library/hh454950.aspx
这是工作控制台应用程序示例。它是非常硬编码的,但我的测试应用程序工作正常,所以我希望它对你有用。
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("App started");
var tokenUrl = "http://localhost:29825/token";
var userName = "stack";
var userPassword = "password";
var request = string.Format("grant_type=password&username={0}&password={1}", HttpUtility.UrlEncode(userName), HttpUtility.UrlEncode(userPassword));
var token = HttpPost(tokenUrl, request);
var url = "http://localhost:29825/api/clients";
var clients = HttpGet(url, token.access_token);
foreach (var client in clients)
{
Console.WriteLine(client.Name);
}
Console.WriteLine("Press Enter to quit");
Console.ReadLine();
}
private static AccessToken HttpPost(string tokenUrl, string requestDetails)
{
WebRequest webRequest = WebRequest.Create(tokenUrl);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
webRequest.ContentLength = bytes.Length;
using (Stream outputStream = webRequest.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
using (WebResponse webResponse = webRequest.GetResponse())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccessToken));
AccessToken token = (AccessToken)serializer.ReadObject(webResponse.GetResponseStream());
return token;
}
}
private static List<Client> HttpGet(string url, string token)
{
WebRequest webRequest = WebRequest.Create(url);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "GET";
webRequest.Headers.Add("Authorization", "Bearer " + token);
using (WebResponse webResponse = webRequest.GetResponse())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Client>));
List<Client> clients = (List<Client>)serializer.ReadObject(webResponse.GetResponseStream());
return clients;
}
}
[DataContract]
public class AccessToken
{
[DataMember]
public string access_token { get; set; }
[DataMember]
public string token_type { get; set; }
[DataMember]
public string expires_in { get; set; }
[DataMember]
public string userName { get; set; }
}
[DataContract]
public class Client
{
[DataMember]
public string Id { get; set; }
[DataMember]
public string Name { get; set; }
}
}
}
答案 1 :(得分:0)
我刚刚设置了Thread.CurrentPrincipal,它现在运行正常。