Функции аннотаций C# AWS Lambda никогда не проходят через промежуточное программное обеспечениеC#

Место общения программистов C#
Ответить
Anonymous
 Функции аннотаций C# AWS Lambda никогда не проходят через промежуточное программное обеспечение

Сообщение Anonymous »

Я пишу функции C# Lambda, которые будут доступны службе шлюза API с использованием AWS Annotation Framework.
Я успешно зарегистрировал службы приложений в ConfigurationServices(IServiceCollection Services) code> файла Startup.cs.
Чтобы добавить некоторые конфигурации API в заголовок всех входящих запросов (заголовок авторизации и т. д.), я зарегистрировал промежуточное программное обеспечение через метод Метод configure(IApplicationBuilder app, IWebHostEnvironment env) файла Startup.cs.
Проблема в том, что приложение полностью игнорирует промежуточное программное обеспечение; другими словами, приложение никогда не проходит через промежуточное программное обеспечение.
Вот мой код:
Лямбда-функция (в файле Function.cs ):
using Amazon.Lambda.Core;
using Amazon.Lambda.Annotations;
using TbTypes.Model.Api.Requests;
using Microsoft.AspNetCore.Mvc;
using FromServicesAttribute = Amazon.Lambda.Annotations.FromServicesAttribute;
using FromBodyAttribute = Microsoft.AspNetCore.Mvc.FromBodyAttribute;
using TbTypes.Services.Thingsboard;
using TbTypes.Model.Api.Reponses;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace TbInterface;

public class Function
{
///
/// Function for requesting TB Devices visible by a User
///
[LambdaFunction()]
[HttpGet("/user/devices/")]
public async Task FetchDevices(
[FromBody] UserDevicesRequestBody body,
ILambdaContext context,
[FromServices] IDeviceService service)
{
// you can replace IDeviceService by a dummy service when reproducing the issue
return await service.FetchDevices(body.claims.TbUserID, body.claims.CognitoUserID);
}
}

Мой файл Startups.cs с регистрацией служб в ConfigurationServices() и регистрацией промежуточного программного обеспечения в методе Configure():
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.Lambda.Annotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Diagnostics;
using TbInterface.Configuration;
using TbInterface.Middlewares;
using TbInterface.Repositories;
using TbInterface.Services.Cache;
using TbInterface.Services.Database;
using TbInterface.Services.Thingsboard;
using TbTypes.Configuration;
using TbTypes.Repositories;
using TbTypes.Services.Cache;
using TbTypes.Services.Thingsboard;

namespace TbInterface
{
[LambdaStartup]
public class Startup
{
private IConfiguration Configuration;

public Startup()
{
Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}

public void ConfigureServices(IServiceCollection services)
{

// Application Configurations
services.AddSingleton(implementationInstance: Configuration);
services.AddSingleton(sp => {
var settings = sp.GetRequiredService();
return new TbConfiguration(settings);
});

// Cache Service: AWS Elasti Cache
services.AddSingleton();

// Database Service: AWS DynamoDB
services.AddSingleton();
services.AddAWSService();
//services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
services.AddAWSService();
services.AddAWSService();

// Repositories
services.AddSingleton();

// Thingsboard API services
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddTransient();

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Here's how I resgistered the middleware
app.UseMiddleware();
}

}
}

Само промежуточное ПО — TbApiConfigurationMiddleware.cs:
using Microsoft.AspNetCore.Http;
using System.Net;
using Newtonsoft.Json;
using TbAPIClient.Generated.Client;
using TbAPIClient.Generated.Model;
using TbClientConfiguration = TbAPIClient.Generated.Client.Configuration;
using TbTypes.Model.Api.Requests;
using TbTypes.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace TbInterface.Middlewares
{
public class TbApiConfigurationMiddleware : IMiddleware
{
///
/// Custom logic to be executed before the next middleware
///
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var authService = context.RequestServices.GetService();

BaseApiRequestBody? body = extractRequestBody(context);

if (body == null || body.claims == null) {
await handleBadRequestBody(context, "Bad request body format");
return;
}

//JwtPair? token = await _authService.RetrieveOrRequestUserToken(body.claims.TbUserID!);
JwtPair? token = await authService!.FetchUserTokenAsync(body.claims.TbUserID!);

if (token == null)
{
await handleUnauthorizedUser(context);
return;
}

var tbConfiguration = context.RequestServices.GetService();
ConfigureTbApiToken(token!, tbConfiguration!);

await next(context);
}

///
/// Extract request body to perform basic format validation
///
/// HTTP Context
///
private BaseApiRequestBody? extractRequestBody(HttpContext context) {
var rawBody = context.Request.Body.ToString();

if (rawBody == null)
{
return null;
}

return JsonConvert.DeserializeObject(rawBody);
}

///
/// Handling bad request body
///
/// HTTP Context
///
private async Task handleBadRequestBody(HttpContext context, string message) {
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.ContentType = "application/json";
var body = new ApiException(context.Response.StatusCode, message);
await context.Response.WriteAsync(JsonConvert.SerializeObject(body));
}

///
/// Configuring middleware response in case of Unauthorized User
///
/// HTTP Context
///
private async Task handleUnauthorizedUser(HttpContext context)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Response.ContentType = "application/json";
var body = new ApiException(context.Response.StatusCode, "Unauthorized user");
await context.Response.WriteAsync(JsonConvert.SerializeObject(body));
}

///
/// Method for configuring Thingsboard API Auth Token
///
/// Token definition: {Token, RefreshToken}
/// Application configs
///
private void ConfigureTbApiToken(JwtPair token, ITbConfiguration tbConfiguration)
{
TbClientConfiguration.Default.ApiKeyPrefix[tbConfiguration.TokenHeaderKey] = tbConfiguration.TokenType;
TbClientConfiguration.Default.ApiKey[tbConfiguration.TokenHeaderKey] = (string)token.Token;
}
}
}



Подробнее здесь: https://stackoverflow.com/questions/792 ... middleware
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»