Giter VIP home page Giter VIP logo

graphiql-dotnet's Introduction

GraphiQL.NET

.NET Core

GraphiQL middleware for ASP.NET Core - try the live demo here.

What is GraphiQL.NET?

GraphiQL.NET is a piece of .NET Core middleware that bundles graphiql into it saving you from managing additional frontend dependencies, whilst also giving you control over the routes it's avaialble on any provide you with a means of authentication.

GraphiQL.NET features include:

  • The full GraphiQl experience
  • Customisation of GraphiQL routes
  • Authentication

GraphiQL for ASP.NET Core

Setup

The GraphiQL.NET middleware can be found on NuGet here

You can install GraphiQL.NET by copying and pasting the following command into your Package Manager Console within Visual Studio (Tools > NuGet Package Manager > Package Manager Console).

Install-Package graphiql

Alternatively you can install it using the .NET Core CLI using the following command:

dotnet add package graphiql

Getting Started

Once installed you can add GraphiQL.NET to your ASP.NET Core application by adding the app.UseGraphiQl() middleware to the Configure method within your Startup.cs file.

Note: Be sure to call UseGraphiQl() before UseMvc().

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Adding this makes graphiql UI available at /graphql 
    app.UseGraphiQl();

    app.UseMvc();
}

Configuration


Configure Graphiql route

By default GraphiQL lives on the /graphql endpoint, however this can be changed by passing your chosen path to the app.UseGraphiQl(); entry point method:

app.UseGraphiQl('/whatever/graphiql');

Configure Graphql API address

You can also specify GraphiQl endpoint independent of your GraphQL API, this is especially useful if you're hosting in IIS in a virtual application (ie myapp.com/1.0/...) or hosting API and documentation separately.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseGraphiQl("/graphql", "/v1/yourapi");

    app.UseMvc();
}

Now navigating to /graphql will display the GraphiQL UI, but your GraphQL API will live under the /v1/yourapi route.

Configuration via IServiceCollection

Alternatively you can configure the aforementioned routes via IServiceCollection within ConfigureServices or your Startup.cs file:

//Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...

	services.AddGraphiQl(x =>
	{
		x.GraphiQlPath = "/graphiql-ui";
		x.GraphQlApiPath = "graphql";
	});

    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
	app.UseGraphiQl();
	...
}

Configuration via ConfigureOptions<T>

You can also use the IConfigureOptions<T> interface:

// GraphiQlTestOptionsSetup.cs

internal class GraphiQlTestOptionsSetup : IConfigureOptions<GraphiQlOptions>
{
    public void Configure(GraphiQlOptions options)
    {
        options.GraphiQlPath = "/graphiql-ui";
        options.GraphQlApiPath = "graphql";
    }
}

Then you just have to register it with your Ioc Container:

//Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<IConfigureOptions<GraphiQlOptions>, GraphiQlTestOptionsSetup>();z
    ...
}
---

graphiql-dotnet's People

Contributors

dependabot[bot] avatar frankyboy avatar jamieped avatar josephwoodward avatar lucas0707 avatar poulad avatar slang25 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphiql-dotnet's Issues

Console error within graphiql-ui (404 POST ERROR)

When I access the GraphiQL endpoint everything shows correct except for the console that shows this error:

image

In the Network tab there is no response, just the 404 error, this also happens when I query something.

This is how I add my services and graphiQL:

services.AddGraphiQl(x =>
{
    x.GraphiQlPath = "/graphiql-ui";
    x.GraphQlApiPath = "graphql";
});
services.AddSingleton<IDependencyResolver>(x => new FuncDependencyResolver(type => x.GetRequiredService(type)));
services.AddScoped<UnitMeasurement>();
services.AddScoped<UnitMeasurementRepository>();
services.AddScoped<UnitMeasurementQuery>();
services.AddScoped<UnitMeasurementSchema>();
services.AddGraphQL(x =>
{
    x.ExposeExceptions = true; //set true only in development mode. make it switchable.
}).AddGraphTypes(ServiceLifetime.Scoped);

Any help is appreciated, thanks.

Cannot find schema

I am unable to run any queries as it does not seem to be able to discover the schema. I do have a GraphQL running on my /api/graphql and have included app.UseGraphiQl(). Are there any other things I need to do?

Support for ASP.NET MVC/WebAPI (non .NET Core)

Would love to have support for ASP.NET (not Core), anyone up for contributing a PR?

I presume this would require the none .NET Core MVC taking a dependency on OWIN to load the middleware.

OAuth integration?

Any ideas on how to integrate OAuth and access tokens into the GraphiQL documentation?

Drop Down Menu Selection Not Executing Correct Operation

In the attached example, the second (or last) operation is run regardless of which selection is made in the drop down menu. Any ideas what could be causing this? Btw, great implementation, the intellisense is amazing.

Thanks

graphiQL-issue

Get tests running in GitHub actions

GitHub action tests currently fail with the following error:

Run dotnet test src/graphiql.tests/ --configuration Development --nologo
##[warning]BaseTest.cs(40,30): warning CS0168: The variable 'e' is declared but never used [/home/runner/work/graphiql-dotnet/graphiql-dotnet/src/graphiql.tests/graphiql.tests.csproj]
Test run for /home/runner/work/graphiql-dotnet/graphiql-dotnet/src/graphiql.tests/bin/Development/netcoreapp3.1/graphiql.tests.dll(.NETCoreApp,Version=v3.1)
Starting test execution, please wait...

A total of 1 test files matched the specified pattern.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured. Key {06adbfda-45e1-4c4d-8b95-3d842d41852f} may be persisted to storage in unencrypted form.
Connection refused Connection refused
Connection refused Connection refused
Connection refused Connection refused
Connection refused Connection refused
Connection refused Connection refused
Connection refused Connection refused
Connection refused Connection refused
Connection refused Connection refused
Connection refused Connection refused
Connection refused Connection refused
Connection refused Connection refused
Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 44539
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Connection refused Connection refused
Connection refused Connection refused
[xUnit.net 00:00:07.45]     GraphiQl.tests.GraphQlTests.CanQueryGraphQl [FAIL]
  X GraphiQl.tests.GraphQlTests.CanQueryGraphQl [1ms]
  Error Message:
   OpenQA.Selenium.WebDriverException : unknown error: Chrome failed to start: exited abnormally.
  (chrome not reachable)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
  Stack Trace:
     at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
   at OpenQA.Selenium.Chrome.ChromeDriver..ctor(ChromeDriverService service, ChromeOptions options, TimeSpan commandTimeout)
   at OpenQA.Selenium.Chrome.ChromeDriver..ctor(ChromeOptions options)
   at GraphiQl.tests.BaseTest..ctor(Boolean runHeadless) in /home/runner/work/graphiql-dotnet/graphiql-dotnet/src/graphiql.tests/BaseTest.cs:line 31
   at GraphiQl.tests.GraphQlTests..ctor(HostFixture fixture) in /home/runner/work/graphiql-dotnet/graphiql-dotnet/src/graphiql.tests/GraphQlTests.cs:line 14

Question: Possible to pass Authorization Header?

My GraphQlController has an [Authorize] attribute applied to it, is there a way to send a header with
Authorize : bearer ... ?

Not much of an issue really, Just want to know if it's possible.

Docs sidebar not working

After integrating the nuget into my GraphQL server, when I launch GraphiQL, it make 2 POST calls to __schema and shows the schema result in the output window but when I opens the Doc pane, it says No Schema Available.

image

Missing schema intellisense

Hi there. I'm having issues getting intellisense to appear with any of the released versions for this package.

When I access the graphiql site, it's making a successful request to obtain the json based graph ql schema. However, i'm not getting an intellisense when I start writing queries, nor do I get the document explorer populating.

Is there something I'm missing?

My app start up looks like the following

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseGraphiQl("/graphql", "/api/graphql");

            app.UseMvc();
        }

where I have a post and get controller at the specified location.

Error 500 while fetching document after version Upgrade of both graphiql and graphql.net

I have upgraded graphql.net library to 4.6.1 and also graphiql version to 2.0.0 but since then I have been facing error when try to open the UI
" The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0. FROM Inner Exception: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. LineNumber: 0 | BytePositionInLine: 0. Exception 9248876d-d7c5-4222-94db-3a2691ced550 The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0. FROM Inner Exception: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. LineNumber: 0 | BytePositionInLine: 0. , StackTrace Exception: at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)\r\n at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)\r\n at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)\r\n at System.Text.Json.JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)\r\n at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, Type returnType, JsonSerializerOptions options)\r\n at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)\r\n "

graphql/ not loading, js error. Can't get schema.

Hello, I tried to setup GraphiQL on dontnet aspnet core 2.1 site, but got follow js error.

invariant@http://localhost:22735/graphql/graphiql.js:24179:11
defineFieldMap@http://localhost:22735/graphql/graphiql.js:27207:4
getFields@http://localhost:22735/graphql/graphiql.js:27164:44
typeMapReducer@http://localhost:22735/graphql/graphiql.js:28869:20
GraphQLSchema@http://localhost:22735/graphql/graphiql.js:28758:21
buildClientSchema@http://localhost:22735/graphql/graphiql.js:30166:10
_fetchSchema/<@http://localhost:22735/graphql/graphiql.js:2140:25

With debugger I figured that comes after try to get schema with follow command


  query IntrospectionQuery {
    __schema {
      queryType { name }
      mutationType { name }
      subscriptionType { name }
      types {
        ...FullType
      }
      directives {
        name
        description
        locations
        args {
          ...InputValue
        }
      }
    }
  }

  fragment FullType on __Type {
    kind
    name
    description
    fields(includeDeprecated: true) {
      name
      description
      args {
        ...InputValue
      }
      type {
        ...TypeRef
      }
      isDeprecated
      deprecationReason
    }
    inputFields {
      ...InputValue
    }
    interfaces {
      ...TypeRef
    }
    enumValues(includeDeprecated: true) {
      name
      description
      isDeprecated
      deprecationReason
    }
    possibleTypes {
      ...TypeRef
    }
  }

  fragment InputValue on __InputValue {
    name
    description
    type { ...TypeRef }
    defaultValue
  }

  fragment TypeRef on __Type {
    kind
    name
    ofType {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
                ofType {
                  kind
                  name
                }
              }
            }
          }
        }
      }
    }
  }

Can you help, what to check to solve that?

Need to import GraphiQl namespace since GraphiQL 1.2.0

Adding the app.UseGraphiQl() middleware does not seem to work in GraphiQL 1.2.0 unless you add using GraphiQl to Startup.cs. In version 1.1.0 it this does not seem to be necessary. This should be explicitly mentioned in the README and also added to the graphiql.example, if it's not considered a regression.

changing /graphql location

Looks like this is not quite working as its supposed to. My understanding is that we need to change the js file aswell if we specify an alternate location

in index.html

function graphQLFetcher(graphQLParams) {
        // This example expects a GraphQL server at the path /graphql.
        // Change this to point wherever you host your GraphQL server.
        return fetch('/graphql', {
          method: 'post',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },

Wanted to see if I could fix it but ran into issues when I tried to reference the source as a project reference.

I pulled the source and did a build, when I referenced the project, I couldn't get the graphiql page to load. The /graphql endpoint was just not serving up the static pages.. Not too sure why. The dll in nuget definitely works so wondering if that is a different version to what is in master?

How to use with .net 4.7

I searched a lot, but I didn't find how to use this package with .net 4.7 (not Core).
The documentation guides you to use IApplicationBuilder that does not exist in this framework.
Is there any place I can read how to do this setup?

Thanks

Don't require path in UseGraphiQl to be absolute

Hi!

TL;DR: we are hosting in a subdirectory (to separate different API versions). Right now we have to call https://github.com/JosephWoodward/graphiql-dotnet/blob/6ff32fb21be3fb30c981d3d0e1dcff06e03811ff/src/graphiql/GraphiQlExtensions.cs#L16 with an absolute path, meaning we have to know the subdirectory we are hosted under. I would argue removing the check on this line https://github.com/JosephWoodward/graphiql-dotnet/blob/6ff32fb21be3fb30c981d3d0e1dcff06e03811ff/src/graphiql/GraphiQlExtensions.cs#L21 does not hurt anyone and gives more flexibility.

Cheers,
FB

Custom js support

There is a lot of issues already that will need to modify the javascript of the library. Some of them are to generic for example there is any standard subscription protocol for graphql at this moment. So allowing some javascript configuration we can choose the fetch for subscriptios for example.

Nuget with latest

Hi,

Saw that you fixed the code to be compatible with netcoreapp2.0 but you havn't released it as nuget.
Could you please do so? :)

/Martin

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.