gpt4 book ai didi

asp.net - 测试受 [Authorize] 保护的 Web API Controller

转载 作者:行者123 更新时间:2023-12-02 10:27:57 24 4
gpt4 key购买 nike

我刚刚使用 ASP.net 身份 OWIN 和 OAuth 2 将基于 token 的安全性添加到我的 Web API 中。因此,我在所有测试中都收到 405 未经授权的错误。我如何模拟安全上下文。我见过一些示例,其中其他示例覆盖了 Thread.CurrentPrincipal,但不确定这是否是正确的方法。

样本测试

    [TestMethod]
public void Verify_GetReferenceData_Http_Get()
{
var configAE = new HttpSelfHostConfiguration("http://localhost:53224");
Konstrukt.SL.AggregationEngine.WebApiConfig.Register(configAE, new AutoFacStandardModule());

using (HttpSelfHostServer serverAE = new HttpSelfHostServer(configAE))
{
serverAE.OpenAsync().Wait();
HttpResponseMessage responseMessage;
using (var client = new HttpClient())
{
responseMessage =
client.GetAsync(
"http://localhost:53224/AggregationEngine/GetReferenceData/1/Dummy/..."
).Result;
serverAE.CloseAsync().Wait();
configAE.Dispose();
Assert.AreEqual(HttpStatusCode.OK, responseMessage.StatusCode, "Wrong http status returned");

}
}

}

示例 Controller

public class GetReferenceDataController : ApiController
{
private readonly IDeserializeHelper _deserializeHelper;
private readonly IGetBudgetData _getBudgetData;
private readonly IRevision _revision;

public GetReferenceDataController(IDeserializeHelper deserializeHelper, IGetBudgetData getBudgetData, IRevision revision)
{
_deserializeHelper = deserializeHelper;
_getBudgetData = getBudgetData;
_revision = revision;
}

[Authorize]
[Route("AggregationEngine/GetReferenceData/{budgetId}/{userId}/{filterJSON}")]
[HttpGet]
public HttpResponseMessage Get(int budgetId, string userId, [FromUri]string filterJSON)
{
FlatBudgetData data = new FlatBudgetData();
IDataQueryFilter dataQueryFilter = _deserializeHelper.DeserializeToFilterObject(EntityType.UserReferenceLine, _revision.GetLatesRevision(budgetId), userId, filterJSON);
data.Data = _getBudgetData.GetData(dataQueryFilter);

string jsonFlatBudget = JsonConvert.SerializeObject(data);

var jsonResponse = new HttpResponseMessage()
{
Content = new StringContent(jsonFlatBudget)
};
jsonResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return jsonResponse;
}
}

最佳答案

我遵循以下堆栈线程中的第一个答案并使其正常工作。 Integration Test Web Api With [Authorize]

关于asp.net - 测试受 [Authorize] 保护的 Web API Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29066079/

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