Task-like objects support in Kestrel - asp.net-core-2.2

I am trying to return task-like object from the controller action:
[HttpGet("test")]
public async FuncAwaitable<string> GetAsync() => "OK";
It works in the VS2019 wizard generated ASP.NET Core solution but fails with Kestrel:
The problem is somewhere in middleware:
ArgumentException
System.ArgumentException: 'this' type cannot be an interface itself.
at System.RuntimeTypeHandle.VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
at System.RuntimeType.GetInterfaceMap(Type ifaceType)
at System.Reflection.RuntimeReflectionExtensions.GetRuntimeInterfaceMap(TypeInfo typeInfo, Type interfaceType)
at Microsoft.Extensions.Internal.AwaitableInfo.IsTypeAwaitable(Type type, AwaitableInfo& awaitableInfo)
at Microsoft.Extensions.Internal.CoercedAwaitableInfo.IsTypeAwaitable(Type type, CoercedAwaitableInfo& info)
at Microsoft.Extensions.Internal.ObjectMethodExecutor..ctor(MethodInfo methodInfo, TypeInfo targetTypeInfo, Object[] parameterDefaultValues)
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Create(MethodInfo methodInfo, TypeInfo targetTypeInfo, Object[] parameterDefaultValues)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvokerCache.GetCachedResult(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext context)
at Microsoft.AspNetCore.Mvc.Internal.ActionInvokerFactory.CreateInvoker(ActionContext actionContext)
at Microsoft.AspNetCore.Mvc.Internal.MvcAttributeRouteHandler.<>c__DisplayClass12_0.<RouteAsync>b__0(HttpContext c)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Shared.AspNetCore.CorrelationHeader.<>c__DisplayClass0_0.<<UseCorrelation>b__0>d.MoveNext() in C:\proj\ah\shared\src\Shared.AspNetCore\AspNetCore\CorrelationHeader.cs:line 16
Any ideas?

Related

Unable to resolve service for type 'Microsoft.Extensions.FileProviders.IFileProvider' while attempting to activate my controller

I have this in my controller
using Microsoft.Extensions.FileProviders;
[ApiController]
[Route("api/[controller]")]
public class PlanningController: ControllerBase
{
private readonly IFileProvider fileProvider;
public PlanningController(IFileProvider fileProvider)
{
this.fileProvider = fileProvider;
}
[HttpGet]
[Route("GetTest")]
public async Task<IActionResult> GetTest()
{
return NotFound();
}
When I call to getTest I get this error
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.FileProviders.IFileProvider' while attempting to activate 'api.Controllers.PlanningController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
Stack Query Cookies Headers Routing
InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.FileProviders.IFileProvider' while attempting to activate 'api.Controllers.PlanningController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass4_0.b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass5_0.g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
I'm using ASP.NET Core 3.1
Any idea, please?
Thanks
Solved
I have added this in Startup.cs to inject in my controller
IFileProvider physicalProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
services.AddSingleton<IFileProvider>(physicalProvider);
Thanks

GraphApi with Hot Chocolate: No valid mutation field

I'm trying to set up an GraphApi with Hot Chocolate in ASP.NET Core.
Now I want to split my application in multiple projects/components.
There's an Users component which has a UsersMutation containing 1 field:
public sealed class UsersMutation
{
public Task CreateUser([Service] ICreateUserMutationHandler handler, CreateUserParameters parameters)
=> handler.Handle(parameters);
}
I try to add it to the GraphQl schema like this:
public sealed class Mutation
{
public UsersMutation Users => new UsersMutation();
}
Configuration:
public static class GraphApiConfiguration
{
public static IServiceCollection AddGraphApi<TQuery, TMutation>(this IServiceCollection services)
where TQuery : class
where TMutation : class
{
services.AddGraphQLServer()
.AddQueryType<TQuery>()
.AddMutationType<TMutation>();
services.AddScoped<TQuery>();
services.AddScoped<TMutation>();
return services;
}
}
Finally in startup.cs:
services.AddGraphApi<Query, Mutation>();
But I get the following error trying to see the schema in the playground:
HotChocolate.SchemaException: For more details look at the `Errors` property.
1. The object type `UsersMutation` has to at least define one field in order to be valid. (HotChocolate.Types.ObjectType<ChocoGraph.Components.Users.GraphApi.UsersMutation>)
at HotChocolate.Configuration.TypeInitializer.Initialize(Func`1 schemaResolver, IReadOnlySchemaOptions options)
at HotChocolate.SchemaBuilder.Setup.InitializeTypes(SchemaBuilder builder, IDescriptorContext context, IReadOnlyList`1 types, LazySchema lazySchema)
at HotChocolate.SchemaBuilder.Setup.Create(SchemaBuilder builder, LazySchema lazySchema, IDescriptorContext context)
at HotChocolate.SchemaBuilder.Create(IDescriptorContext context)
at HotChocolate.SchemaBuilder.HotChocolate.ISchemaBuilder.Create(IDescriptorContext context)
at HotChocolate.Execution.RequestExecutorResolver.CreateSchemaAsync(NameString schemaName, RequestExecutorSetup options, RequestExecutorOptions executorOptions, IServiceProvider serviceProvider, TypeModuleChangeMonitor typeModuleChangeMonitor, CancellationToken cancellationToken)
at HotChocolate.Execution.RequestExecutorResolver.CreateSchemaServicesAsync(NameString schemaName, RequestExecutorSetup options, CancellationToken cancellationToken)
at HotChocolate.Execution.RequestExecutorResolver.GetRequestExecutorNoLockAsync(NameString schemaName, CancellationToken cancellationToken)
at HotChocolate.Execution.RequestExecutorResolver.GetRequestExecutorAsync(NameString schemaName, CancellationToken cancellationToken)
at HotChocolate.Execution.RequestExecutorProxy.GetRequestExecutorAsync(CancellationToken cancellationToken)
at HotChocolate.AspNetCore.HttpPostMiddleware.HandleRequestAsync(HttpContext context, AllowedContentType contentType)
at HotChocolate.AspNetCore.HttpPostMiddleware.InvokeAsync(HttpContext context)
at HotChocolate.AspNetCore.WebSocketSubscriptionMiddleware.InvokeAsync(HttpContext context)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.10\System.Buffers.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The program '[44280] iisexpress.exe: Program Trace' has exited with code 0 (0x0).
The program '[44280] iisexpress.exe' has exited with code -1 (0xffffffff).
What am I missing to achieve this? This seemed to work fine if I had the CreateUser field in the Mutation.cs file, but adding this extra step seems to break it.
I found the issue:
Mutation has to return something in order to be a valid field.

Exception has been thrown by the target of an invocation in asp.net core and postgresql migration

I am trying to create a project. That's why I downloaded a startup template from this link. Then I tried to configure with asp.net core. I set the connection string as "Default": "User ID=postgres;Password=**********;Host=localhost;Port=5432;Database=LibraryManagementDb;Pooling=true;". and then changed UseSqlServer to UseNpgsql in LibraryManagementDbContextConfigurer class.
`
public static void
Configure(DbContextOptionsBuilder<LibraryManagementDbContext>
builder, string connectionString)
{
builder.UseNpgsql(connectionString);
}
public static void
Configure(DbContextOptionsBuilder<LibraryManagementDbContext>
builder, DbConnection connection)
{
builder.UseNpgsql(connection);
}
`
and add the below code to DbContext class
`
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(p => p.Value)
.HasMaxLength(100); // any integer that is smaller than 10485760
}
`
and removed all migration classes from the Migration folder and run add-migration Initial_Migration command in the package manager console
but I got the Exception has been thrown by the target of an invocation. error
this is the whole exception
`
PM> add-migration Initial_Migration
Build started...
Build succeeded.
System.Reflection.TargetInvocationException: Exception has been
thrown by the target of an invocation.
---> System.TypeLoadException: Method 'get_Info' in type
'Microsoft.EntityFrameworkCore.Infrastructure.
Internal.NpgsqlOptionsExt
ension' from assembly 'Npgsql.EntityFrameworkCore.PostgreSQL,
Version=2.1.0.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7'
does not have an implementation.
at Microsoft.EntityFrameworkCore
.NpgsqlDbContextOptionsExtensions.UseNpgsql[TContext]
at LibraryManagement.EntityFrameworkCore
.LibraryManagementDbContextConfigurer
.Configure(DbContextOptionsBuilder`1 builder, String
connectionString) in D:\6.0.0\aspnet-
core\src\LibraryManagement.EntityFrameworkCore
\EntityFrameworkCore\LibraryManagementDbContextConfigurer.cs:line
10
at LibraryManagement.EntityFrameworkCore
.LibraryManagementDbContextFactory.CreateDbContext(String[] args)
in D:\6.0.0\aspnet-core\src\LibraryManagement.EntityFrameworkCore
\EntityFrameworkCore\LibraryManagementDbContextFactory.cs:line 17
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor, Boolean
wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,
BindingFlags invokeAttr, Binder binder, Object[] parameters,
CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[]
parameters)
at Microsoft.EntityFrameworkCore.Design
.Internal.DbContextOperations.CreateContextFromFactory(Type
factory,
Type contextType)
at
Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.
<>c__DisplayClass16_0.<FindContextFactory>b__1()
at Microsoft.EntityFrameworkCore.Design.Internal
.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal
.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal
.MigrationsOperations.AddMigration(String name, String outputDir,
String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.AddMigrationImpl(String name, String outputDir, String
contextType,
String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.OperationBase.Execute(Action action)
Exception has been thrown by the target of an invocation.
`
How can I resolve this??? Please help...
By updating 'Npgsql.EntityFrameworkCore.PostgreSQL' solved this problem

Adding a CSV file ASP.NET

Currently on a project to create a check-in system and I'm creating this in ASP.NET MVC. I'm at the stage where I'm in my ImportController and using the Nuget package CsvHelper.
I'm getting errors including 'No overload for method 'Add' takes 3 arguments. Is anyone able to help? I've included a snip of my code below.
Any help would be much appreciated :)
[Route("import")]
public class ImportController : Controller
{
private readonly AppDbContext _appDbContext;
public ImportController(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
[HttpGet("")]
public IActionResult Index()
{
return View();
}
public IActionResult Index(ImportIndexViewModel vm)
{
if (ModelState.IsValid)
{
using (var csvStream = new StreamReader(vm.File.OpenReadStream()))
using (var csv = new CsvReader(csvStream))
{
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
try
{
// Application reference
var AdmissionNumber = csv["Admission Number"];
var Firstname = csv["Students Firstname"];
var Surname = csv["Students Surname"];
if (string.IsNullOrWhiteSpace(AdmissionNumber))
throw new NullReferenceException("admissionNumber");
if (string.IsNullOrWhiteSpace(Firstname))
throw new NullReferenceException("Forename");
if (string.IsNullOrWhiteSpace(Surname))
throw new NullReferenceException("Surname");
// Add student to system
_appDbContext.Students.Add(AdmissionNumber.Trim(), Firstname.Trim(), Surname.Trim());
}
catch (NullReferenceException ex)
{
throw;
Console.WriteLine($"'{ex.Message}' is missing from row {csv.Context.Row}");
}
}
}
}
return View(vm);
}
}
}
Here is the exception stack it's providing me when I click upload. I think this again is due to this line here: _appDbContext.Students.Add(AdmissionNumber.Trim(), Firstname.Trim(), Surname.Trim());
System.InvalidOperationException: Could not create an instance of type 'System.Func`1[[SelfRegister.WebApp.Models.StudentsIndexViewModel+StudentViewModel, SelfRegister.WebApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the '_appDbContext' parameter a non-null default value.
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.BindModelCoreAsync(ModelBindingContext bindingContext, Int32 propertyData)
at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Mvc 4 Routing in sitecore WebForms application System.Web.AsyncStepCompletionInfo.RegisterBeginUnwound NullReferenceException

I'm trying to get Mvc4 routing set up in an existing sitecore WebForms application.
I've added the following:
routes.MapPageRoute("WebForm", "WebForm", "~/WebForm1.aspx");
Navigating to /WebForm gives the following exception:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.AsyncStepCompletionInfo.RegisterBeginUnwound(IAsyncResult asyncResult, Boolean& operationCompleted, Boolean& mustCallEndHandler) +32
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +516
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +287
I faced with the same exception when enabled MVC on Sitecore CMS. I found that the reason is that Sitecore accepts only IAsyncHttpHandler routes.
Technically Sitecore.Mvc.Pipelines.Loader.InitializeRoutes pipeline wraps your handler with RouteHandlerWrapper and invokes it through async RouteHttpHandler that throws the exception in case your handler is not inherited from IHttpAsyncHandler.
To avoid it you should register your routes after Sitecore.Mvc.Pipelines.Loader.InitializeRoutes pipeline in Sitecore.Mvc.config:
<initialize>
<processor type="Sitecore.Mvc.Pipelines.Loader.InitializeGlobalFilters, Sitecore.Mvc"/>
<processor type="Sitecore.Mvc.Pipelines.Loader.InitializeControllerFactory, Sitecore.Mvc"/>
<processor type="Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc"/>
<!-- Register your routes here -->
</initialize>
Alternatively you can make you handler to work asynchronous:
public class MyHandler : IHttpAsyncHandler
{
public void ProcessRequest(HttpContext context)
{
// do your work here
}
public bool IsReusable { get { return false; } }
protected delegate void AsyncProcessorDelegate(HttpContext context);
private AsyncProcessorDelegate _processorDelegate;
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
_processorDelegate = new AsyncProcessorDelegate(ProcessRequest);
return _processorDelegate.BeginInvoke(context, cb, extraData);
}
public void EndProcessRequest(IAsyncResult result)
{
_processorDelegate.EndInvoke(result);
}
}

Resources