如何使用ASP.NET Core 2中间件包装graphql.net端点响应?

时间:2018-11-08 19:00:09

标签: c# json asp.net-web-api2 asp.net-core-2.0

我有使用asp.net Web api2开发的REST API。我正在使用asp.net core 2将REST API迁移到GraphQL.net端点。在现有的REST API代码中,我有一个Delegating处理程序,用于使用其他数据扩展REST API调用的结果,在这种情况下,将本地化数据添加到由于没有在ASP.NET Core 2中支持Delegating处理程序。我试图将现有的Delegating处理程序迁移到Middleware组件。

出于参考目的,我遵循了official guideExtending WebApi response using OWIN Middleware

我这里有几个查询:

  1. 如果使用Middlware,如何映射以下代码? var response = await base.SendAsync(request,cancelToken);

  2. 我应该将中间件放在Startup.cs Configure方法中的什么位置。

  3. 等效于现有委托处理程序的中间件

代码:

public class CommonResponserHandler : DelegatingHandler
{
    ICommonService _commonService = new CommonService();
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        string locale = string.Empty;
        if (request.Headers.Contains("Accept-Language"))
        {
            locale = request.Headers.GetValues("Accept-Language").First();
        }

        bool initialAuthorizationStatus = GetInitialAuthorization(request);
        var response = await base.SendAsync(request, cancellationToken);
        APIResult commonResponse;
        if (response.TryGetContentValue<APIResult>(out commonResponse))
        {
            //populate common response here;
            UpdateCommonResponse(request, response, commonResponse);
            //UpdateCommonResponse(basicResponse, commonResponse);
            HttpResponseMessage newResponse;
            bool authorizatinCheckResult = AssertAuthorization(initialAuthorizationStatus, request);
            if (authorizatinCheckResult)
            {
                newResponse = request.CreateResponse(response.StatusCode, commonResponse);
            }
            else
            {
                var unAuthorisedResult = new APIResult{Authorized = false, UserMessage = Constants.Unauthorized, Locale = new Locale(_commonService.GetLanguageFromLocale(locale))};
                newResponse = request.CreateResponse(HttpStatusCode.Unauthorized, unAuthorisedResult);
                var jsonSerializerSettings = new JsonSerializerSettings{ContractResolver = new CamelCasePropertyNamesContractResolver()};
                HttpContext.Current.Items["401message"] = JsonConvert.SerializeObject(unAuthorisedResult, Formatting.Indented, jsonSerializerSettings);
            }

            //Add headers from old response to new response
            foreach (var header in response.Headers)
            {
                newResponse.Headers.Add(header.Key, header.Value);
            }

            return newResponse;
        }

        return response;
    }
}

有人可以帮助我提供解决问题的指南吗?

1 个答案:

答案 0 :(得分:0)

请阅读ASP.NET Core Middleware documentation,以更好地了解中间件的工作原理。

中间件在其构造函数中接受下一个RequestDelegate并支持Invoke方法。例如:

 public class CommonResponserMiddleware
{
    private readonly RequestDelegate _next;

    public CommonResponserMiddleware(RequestDelegate next)
    {
        _next = next;

    }

    public async Task Invoke(HttpContext context)
    {
        //process context.Request

        await _next.Invoke(context);

        //process context.Response

    }
}

public static class CommonResponserExtensions
{
    public static IApplicationBuilder UseCommonResponser(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CommonResponserMiddleware>();
    }
}

并在Starup.cs中使用:

public void Configure(IApplicationBuilder app) {
    //...other configuration

    app.UseCommonResponser();

    //...other configuration
}

您还可以参考相关的SO问题:

Registering a new DelegatingHandler in ASP.NET Core Web API

How can I wrap Web API responses(in .net core) for consistency?