gpt4 book ai didi

asp.net-web-api - 如何在 AuthorizeAttribute 中获取当前的 HttpContextBase?

转载 作者:行者123 更新时间:2023-12-05 01:04:45 27 4
gpt4 key购买 nike

我需要掌握当前HttpContextBase在 ASP.NET WEB API 中 AuthorizeAttribute .

我如何从 HttpActionContext 获得该信息覆盖的 IsAuthorized() 中的参数?

protected override bool IsAuthorized(HttpActionContext actionContext)
{
// need to call code that requires the current Controllers HttpContextBase
}

最佳答案

所以我最终使用了这个答案中描述的 HttpContextFactory 方法:
https://stackoverflow.com/a/9624433/3584

public class HttpContextFactory
{
private static HttpContextBase m_context;
public static HttpContextBase Current
{
get
{
if (m_context != null)
return m_context;

if (HttpContext.Current == null)
throw new InvalidOperationException("HttpContext not available");

return new HttpContextWrapper(HttpContext.Current);
}
}

public static void SetCurrentContext(HttpContextBase context)
{
m_context = context;
}
}

我将需要当前 HttpContext 的所有代码替换为:
HttpContextFactory.Current...

在我的单元测试中,我这样做:
HttpContextFactory.SetCurrentContext(GetMockedHttpContext());

模拟的上下文:
private HttpContextBase GetMockedHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
var urlHelper = new Mock<UrlHelper>();

var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
var requestContext = new Mock<RequestContext>();
requestContext.Setup(x => x.HttpContext).Returns(context.Object);
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
user.Setup(ctx => ctx.Identity).Returns(identity.Object);
identity.Setup(id => id.IsAuthenticated).Returns(true);
identity.Setup(id => id.Name).Returns("test");
request.Setup(req => req.Url).Returns(new Uri("http://www.google.com"));
request.Setup(req => req.RequestContext).Returns(requestContext.Object);
requestContext.Setup(x => x.RouteData).Returns(new RouteData());
request.SetupGet(req => req.Headers).Returns(new NameValueCollection());

return context.Object;
}

关于asp.net-web-api - 如何在 AuthorizeAttribute 中获取当前的 HttpContextBase?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22568065/

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