2

我使用 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");
    }
}

任何人都可以帮助我提供解决问题的指导吗?

4

1 回答 1

7

最简单的方法是使用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...)
        );
    }
}
于 2018-11-08T18:31:25.577 回答