san*_*tro 2 c# graphql graphql-dotnet asp.net-core-2.1
我使用 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 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");
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我提供解决问题的指导吗?
最简单的方法是使用IHttpContextAccessor. 注册IHttpContextAccessor为单身人士。
https://adamstorr.azurewebsites.net/blog/are-you-registering-ihttpcontextaccessor-correctly
在StartUp.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
Run Code Online (Sandbox Code Playgroud)
GraphQL 类:
public class TestQuery : ObjectGraphType<object>
{
public TestQuery(ITestService testService, IHttpContextAccessor accessor)
{
Field<TestResultType>(
"result",
description: "Test data",
resolve: context => testService.GetDetailsForLocation(accessor.HttpContext...)
);
}
}
Run Code Online (Sandbox Code Playgroud)