在asp.net core 2 graphql端点的情况下,如何提取请求标头并将其传递给业务逻辑?

时间:2018-11-06 18:34:31

标签: c# graphql asp.net-core-2.1 graphql-dotnet

我有以下使用ASP.NET Web API 2和EntityFramework 6开发的代码段。

public class TestController : BaseApiController
{
    private readonly ITestService _testService;
    private readonly ICommonService _commonService;
    private readonly IImageService _imageService;
    public TestController(ITestService testService, ICommonService commonService, IImageService imageService)
    {
        _testService = testService;
        _commonService = commonService;
        _imageService = imageService;
    }

    [Route("test")]
    public IHttpActionResult Get()
    {
        var resp = _testService.GetDetailsForLocation(locale);
        return Ok(resp);
    }
}

public class BaseApiController : ApiController
{
    public string locale
    {
        get
        {
            if (Request.Headers.Contains("Accept-Language"))
            {
                return Request.Headers.GetValues("Accept-Language").First();
            }
            else
            {
                return string.Empty;
            }
        }
    }

    public string GetCookieId()
    {
        string value = string.Empty;
        IEnumerable<CookieHeaderValue> cookies = this.Request.Headers.GetCookies("mycookie");
        if (cookies.Any())
        {
            IEnumerable<CookieState> cookie = cookies.First().Cookies;
            if (cookie.Any())
            {
                var cookieValue = cookie.FirstOrDefault(x => x.Name == "mycookie");
                if (cookieValue != null)
                    value = cookieValue.Value.ToLower();
            }
        }

        return value;
    }
}

我正在使用asp.net core 2和graphql.net将现有的restapi端点转换为graphql端点。在下面的方法中,目前我正在发送“ en”作为值,但是我希望像在上述实现中的asp.net Web api 2一样准确地传递语言环境值。

在这里,我想知道什么是读取请求标头并将值传递给业务loigc的最佳方法(即,在这种情况下,传递给方法:GetDetailsForLocation(“ en”)

public class TestQuery : ObjectGraphType<object>
{
    public TestQuery(ITestService testService)
    {
        Field<TestResultType>("result", resolve: context => testService.GetDetailsForLocation("en"), description: "Test data");
    }
}

有人可以帮助我提供解决问题的指南吗?

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用IHttpContextAccessor。将IHttpContextAccessor注册为单例。

https://adamstorr.azurewebsites.net/blog/are-you-registering-ihttpcontextaccessor-correctly

StartUp.cs中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

GraphQL类:

public class TestQuery : ObjectGraphType<object>
{
    public TestQuery(ITestService testService, IHttpContextAccessor accessor)
    {
        Field<TestResultType>(
            "result",
            description: "Test data",
            resolve: context => testService.GetDetailsForLocation(accessor.HttpContext...)
        );
    }
}