在支持方法调用中不能引用HttpContext

时间:2019-04-28 21:11:32

标签: c# asp.net-core razor

我需要在.NET Core网站上的多个位置使用两个步骤。我决定在Startup.cs中实现一个接口和支持类,以便可以使用DI将对象注入到项目中各个Razor页面上的PageModel中。

Startup.cs

services.AddSingleton<IAuthenticatedGraphClient, AuthenticatedGraphClient>();

接口:

public interface IAuthenticatedGraphClient
{
    Task<GraphServiceClient> GetAuthenticatedGraphClientAsync(HttpContext httpContext);
}    

实施课程:

public class AuthenticatedGraphClient : IAuthenticatedGraphClient
{
    private ITokenAcquisition tokenAcquisition;

    public AuthenticatedGraphClient(ITokenAcquisition tokenAcquisition)
    {
        this.tokenAcquisition = tokenAcquisition;
    }

    public async Task<GraphServiceClient> GetAuthenticatedGraphClientAsync(HttpContext httpContext)
    {
        var accessToken = await TokenAcquisition.GetAccessTokenOnBehalfOfUser(httpContext, new[] { ScopeConstants.ScopeUserRead });

        return new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
            requestMessage
                .Headers
                .Authorization = new AuthenticationHeaderValue("bearer", accessToken);
            return Task.FromResult(0);
        }));
    }
}

PageModel:

public class TestPageModel : PageModel
{
    private IAuthenticatedGraphClient graphClient;

    public TestPage(IAuthenticatedGraphClient graphClient)
    {
        this.graphClient = graphClient;
    }

    public async Task OnPostAsync()
    {
        var graphServiceClient = await graphClient.GetAuthenticatedGraphClientAsync(HttpContext);
        //truncated for brevity...
    }
}

我以为我必须将HttpContext类中的PageModel提供给被调用的方法,但是我不确定,因为这会给我一个错误:

  

非静态字段,方法或属性'TokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext,IEnumerable,string)'需要对象引用

我也尝试过:

var accessToken = await TokenAcquisition.GetAccessTokenOnBehalfOfUser(HttpContext, new[] { ScopeConstants.ScopeUserRead });

...但是这给了我错误:

  

'HttpContext'是一种类型,在给定的上下文中无效

如果我将GetAuthenticatedGraphClientAsync作为方法放在同一PageModel类中,则它可以正常工作并且可以理解HttpContext

有什么想法吗?有更好的模式吗?

1 个答案:

答案 0 :(得分:1)

关于所需的对象引用的第一个错误似乎是因为您的AuthenticatedGraphClient构造函数采用了一个ITokenAcquisition参数,您似乎并没有在Startup.cs中传递该参数

至于关于HttpContext是类型的第二个错误,是的,我很确定您应该将HttpContext.Current传递到GetAccessTokenOnBehalfOfUser中。

编辑:而且,您甚至都没有使用传入的ITokenAcquisition

var accessToken = await TokenAcquisition.GetAccessTokenOnBehalfOfUser(httpContext, new[] { ScopeConstants.ScopeUserRead });

应为:

var accessToken = await tokenAcquisition.GetAccessTokenOnBehalfOfUser(httpContext, new[] { ScopeConstants.ScopeUserRead });