I am using .NET 8 and Kestrel. I am trying to get the class type for any Post or Put requests.
My endpoint code looks something like this:
endpoints.MapPost($"{_basePath}/registerMyObject", [AllowAnonymous] async ([FromBody] MyOject myObject) =>
{
// my code
}
My middleware looks something like:
public class ValidateModelMiddleware : IMiddleware
{
private ITokenService _tokenService;
private IServiceProvider _serviceProvider;
public ValidateModelMiddleware([FromServices] ITokenService tokenService, [FromServices] IServiceProvider serviceProvider)
{
_tokenService = tokenService;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (context.Request.Method == "POST" || context.Request.Method == "PUT")
{
// I need to figure out the type that was passed in. For instance
}
}
So when a registerMyObject request is received I want to get the Type MyOject so that I can deserilize that json text directly into that class. And if a different Post / Put request is used and it has a different class type then I want to get that corresponding type. Is there anyway to do this?
You could choose which type to de-serialize depending on if the jsonstring "keys" matches which class type fileds. For instance:
If there are
ClassAandClassBboth implementMyObject.You could use following code to get a "classResult" string which matches jsonstring.