Hotchocolate: How best to gain access to the HttpRequest object in my Query

Created on 2 Sep 2019  ยท  3Comments  ยท  Source: ChilliCream/hotchocolate

What would be the best method of gaining access to the HttpRequest object of the current request in my query. I have some code like this

```
public class Query
{
    public async Task<IEnumerable<Address>> AddressAccess()
    {

        var addresses = new[]
        {
            new Address
            {
                AddressId = "Test"
            }
        };

        return addresses;
    }
}

```

Normally in a web api i would just use Request.Headers, i need this object so i can pass some extra data from the headers into my query

โ“ question

Most helpful comment

@michaelstaib Point #2 worked great thank you!

For anyone following this issue my code now looks like:

```
public class Query
{
private IHttpContextAccessor _contextAccessor;

    public Query(HttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public async Task<IEnumerable<Address>> AddressAccess()
    {
        //Use _contextAccessor here

        return new Address[]
        {
            new Address(), 
        };
    }
}

```

All 3 comments

There are two ways to do it.

  1. Write a request interceptor and copy the needed headers into the context data. This will keep your graphql layer clean from http types and lets you write simpler tests.

  2. Use IHttpContextAccessor in your resolver.

I will post some code later today

@michaelstaib Point #2 worked great thank you!

For anyone following this issue my code now looks like:

```
public class Query
{
private IHttpContextAccessor _contextAccessor;

    public Query(HttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public async Task<IEnumerable<Address>> AddressAccess()
    {
        //Use _contextAccessor here

        return new Address[]
        {
            new Address(), 
        };
    }
}

```

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nigel-sampson picture nigel-sampson  ยท  5Comments

sgt picture sgt  ยท  4Comments

acelot picture acelot  ยท  4Comments

lTimeless picture lTimeless  ยท  5Comments

nigel-sampson picture nigel-sampson  ยท  5Comments