【问题标题】:Sending multipart/form-data using GraphQL API in .NetCore在 .Net Core 中使用 GraphQL API 发送多部分/表单数据
【发布时间】:2021-12-15 05:15:25
【问题描述】:

我正在尝试使用 GraphQL API 将 .png/jpeg/.jpg 文件类型的用户头像从 Angular 客户端上传到 .netCore 服务器应用程序。 我设法从客户端以内容类型multipart/form-data 的请求发送要上传的图像。 但从 API 服务器收到 400 错误,说明不支持该内容类型。

错误信息如下:

消息:“无效的‘Content-Type’标头:不支持的媒体类型。 必须是“application/json”、“application/graphql”或“application/x-www-form-urlencoded”。见:http://graphql.org/learn/serving-over-http/."

我正在尝试像这样实现突变。

FieldAsync<StringGraphType>(
            "testImageUpload",
            arguments: new QueryArguments(
                new QueryArgument<StringGraphType> { Name = "testArg" },
                new QueryArgument<UploadGraphType> { Name = "file" }
                ),
            resolve: async context =>
            {
                var testArg = context.GetArgument<string>("testArg");
                var file = context.GetArgument<IFormFile>("file");

                try
                {
                    return await uploaderService().UploadImage(file);
                }
                catch (Exception e)
                {
                    context.Errors.Add(new ExecutionError("Something happened!"));
                    return context.Errors;
                }
            });

我使用GraphQL.netGraphQL.Upload.AspNetCore 来支持多部分文件。

样本突变将是这样的:

mutation testImageUpload($testArg: String, $file: Upload) {
  fileUpload{
    testImageUpload(testArg: $testArg, file: $file)
  }
}

任何人都可以向我建议如何使 .NetCore webAPI 应用程序接受multipart/form-data。 任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: .net-core graphql asp.net-core-webapi graphql-dotnet apollo-angular


    【解决方案1】:

    我也遇到了这个问题。答案就在您的Startup.cs 文件中。

    首先,即使在使用 GraphQL.Upload 时出现“Invalid 'Content-Type' header”的原因是(在给出这个答案时)GraphQL.net 中间件只检查三种不同的 Content-Type如果这些都不匹配,则标头和错误。 See GitHub

    至于解决方案,您尚未共享任何 Startup.cs 文件,因此我不确定您的文件是什么样的。我会分享我的相关部分。

    您需要添加服务和中间件。

    服务:

    services.AddGraphQLUpload()
      .AddGraphQL((options, provider) =>
      {
      ...
      });
    

    如果您使用端点映射到中间件,则需要添加 UseGraphQLUpload 中间件,然后映射您的端点。

    例子:

      app.UseGraphQLUpload<YourSchema>("/api/graphql", new 
      GraphQLUploadOptions {
        UserContextFactory = (ctx) => new GraphQlUserContext(ctx.User)
      });
      app.UseEndpoints(endpoints =>
      {
        // map HTTP middleware for YourSchema at path api/graphql
        endpoints
          .MapGraphQL<YourSchema, GraphQLMiddleware<YourSchema>>("api/graphql")
          .RequireAuthorization();
        ...
        // Additional endpoints
        ...
       }
    

    在我看来其他一切都很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-14
      • 2021-03-14
      • 2015-06-23
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2014-01-10
      相关资源
      最近更新 更多