我使用 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 一样。
在这里我想知道读取请求 header 并将值传递给业务 loigc 的最佳方法是什么(即在这种情况下传递给方法:GetDetailsForLocation("en")
public class TestQuery : ObjectGraphType<object>
{
public TestQuery(ITestService testService)
{
Field<TestResultType>("result", resolve: context => testService.GetDetailsForLocation("en"), description: "Test data");
}
}
任何人都可以帮助我提供解决问题的指导吗?
最佳答案
最简单的方法是使用 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...)
);
}
}
关于c# - 在 asp.net core 2 graphql 端点的情况下,如何提取请求 header 并将其传递给业务逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53177945/