gpt4 book ai didi

asp.net-mvc - 如何使用授权属性进行 ASP.NET Web API 集成测试

转载 作者:行者123 更新时间:2023-12-01 06:37:27 34 4
gpt4 key购买 nike

我确实在我的 Web API 上应用了授权属性。
我正在从 MVC4 应用程序调用 Web API,在该应用程序中我使用了基于标准 cookie 的身份验证。
我需要从集成测试中调用 Controller 上的 Web API 方法,但由于应用了授权属性,我将始终收到 未授权异常 .

解决这个问题的最佳方法是什么?
附注。我不想(需要)使用其他身份验证方法,例如 Auth Header 中的 APIKey、Token 和类似的...

最佳答案

首先,回答这个问题的一个关键要素是了解您使用的是哪种身份验证机制。例如,如果您使用基本身份验证,则可以在集成测试时发送凭据:

[Fact]
public async Task FooTest() {

var username = "user";
var password = "supersecret";

// construct your config here as I do below.
// RouteConfig and WebAPIConfig are my own classes
var config = new HttpConfiguration();
RouteConfig.RegisterRoutes(config);
WebAPIConfig.Configure(config);

var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/cars");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

request.Headers.Authorization = new AuthenticationHeaderValue(
"Basic", EncodeToBase64(string.Format("{0}:{1}", username, password)));

using (var httpServer = new HttpServer(config))
using (var client = new HttpClient(httpServer)) {

var response = await client.SendAsync(request);
var result = await response.Content.ReadAsAsync<Car>();

// do you test now...
}
}

private static string EncodeToBase64(string value) {

byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(value);
return Convert.ToBase64String(toEncodeAsBytes);
}

当然,处理身份验证的处理程序应该能够使用这些凭据对您进行身份验证。

另一方面,由于您将在内存中托管应用程序,请将经过身份验证的主体设置为 Thread.CurrentPrincipal将是另一种选择,但不会是我最喜欢的选择。

关于asp.net-mvc - 如何使用授权属性进行 ASP.NET Web API 集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13626042/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com