ASP.NET Core 6 MVC - The view 'Index' was not found - asp.net-core

I can run my asp.net 6 mvc app in VS2022 with no issues. When I publish to a folder and deploy to IIS or run the exe myself I get an error 'the view Index was not found'.
The search locations reported are correct. My views are in the correct folder.
I have also added Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation nuget package and updated Program.cs:
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
The *.cshtml files Build Action are set to Content in Visual Studio.
Nothing suggested in various stackoverlow posts resolves the issue. The majority are related to a VS2022 issue requiring Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package to be added.
I've set stdoutLogEnabled="true" and verified the log generated when running through IIS matches the log output when calling the .exe. I don't believe this is an IIS issue.
Below is my Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
app.UseExceptionHandler("/Home/Error");
app.UseStatusCodePagesWithReExecute("/Home/Error", "?code={0}");
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Nothing of interest in appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
The project file is as follows:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>MyFirstApp.MVC</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.123" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.10" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="7.0.2" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.4" />
<PackageReference Include="System.DirectoryServices.AccountManagement" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\images\" />
</ItemGroup>
</Project>
Below is the error log. Logging added to confirm Controller action method is completing with no error:
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: D:\Projects\ReportViewer
**info: ReportViewer.MVC.Controllers.HomeController[0]
Into Index**
**info: ReportViewer.MVC.Controllers.HomeController[0]
About to return view Index**
fail: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[3]
The view 'Index' was not found. Searched locations: /Views/Home/Index.cshtml, /Views/Shared/Index.cshtml
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml
at Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable`1 originalLocations)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_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 ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
fail: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[3]
The view 'Error' was not found. Searched locations: /Views/Home/Error.cshtml, /Views/Shared/Error.cshtml
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[3]
An exception was thrown attempting to execute the error handler.
System.InvalidOperationException: The view 'Error' was not found. The following locations were searched:
/Views/Home/Error.cshtml
/Views/Shared/Error.cshtml
I'd really appreciate any suggestions you may have.
Thanks,
Lance

Turns out the publish step in VS was failing to resolve some MVC Analyser dlls. Despite this, it was still reporting the publish succeeded and generated the dlls and exe files.
Only spotted the publishing issue after scrolling through the publish output log for any clues.
Publishing problem was caused by having two versions of .NET6 installed on the dev machine. I removed the older version and updated dotnet environment variables to point to dotnet6 located in C:\Program Files....that broke the Dependency Frameworks in the MVP Project. The Path and Version entries were blank for Microsoft.AspnetCore.App and Microsoft.NETCore.App.
Under time pressure so created a new MVC project, copied all files across to this new project, published and deployed to IIS with no issues.

Related

Import method of windows security encryption algorithm is not working in hosting environment

I need to use RSA cryptography for encryption of data. I have used ImportPkcs8PrivateKey method of System.Security.Cryptography for importing private key. The code working fine in visual studio but only ImportPkcs8PrivateKey method is not working in hosting server. My Hosting server is windows 2019 and I have installed all hosting package.
var privateKeyBytes = Convert.FromBase64String(marchentPrivateKey);
int myarray;
var rsa = RSA.Create();
rsa.ImportPkcs8PrivateKey(privateKeyBytes, out myarray);
return rsa;
The following Error trace is generated in hosted server
at lambda_method(Closure , Object )
at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
Actually its issue of IIS setting. Cryptographic Service Provider try to store a key for certificate in the user store and if a profile was not available, a cryptographic context was not available. By default IIS Load User Profile is false. See for more details
What exactly happens when I set LoadUserProfile of IIS pool?

Issue restoring local NuGet package through Azure Pipelines

I have come across an issue in Azure Pipelines where I have a local NuGet package in my repo that I wish to include in the pipelines build alongside all other NuGet packages (which are all picked up from nuget.org normally). My project is built on ASP.NET Core, more specifically it is a Blazor server-side web application.
The local NuGet package "Breeze.Sharp.0.9.6.nupkg" is stored in my repo under: MySolution/packages
What is happening is that the nuget.org packages restore OK in pipelines but it fails when it tries to find my local NuGet package location and throws the below error:
1>/usr/share/dotnet/sdk/3.1.402/NuGet.targets(128,5): error : The local source '/home/vsts/work/1/Nuget/MySolution/packages' doesn't exist. [/home/vsts/work/1/s/MySolution/MySolution.sln]
NuGet.Protocol.Core.Types.FatalProtocolException: The local source '/home/vsts/work/1/Nuget/MySolution/packages' doesn't exist.
at NuGet.Protocol.LocalV3FindPackageByIdResource.GetVersionsCore(String id, ILogger logger)
at NuGet.Protocol.LocalV3FindPackageByIdResource.<>c__DisplayClass22_0.<GetVersions>b__0(String keyId)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at NuGet.Protocol.LocalV3FindPackageByIdResource.GetVersions(String id, SourceCacheContext cacheContext, ILogger logger)
at NuGet.Protocol.LocalV3FindPackageByIdResource.GetAllVersionsAsync(String id, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.Commands.SourceRepositoryDependencyProvider.GetAllVersionsAsync(String id, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.Commands.SourceRepositoryDependencyProvider.FindLibraryCoreAsync(LibraryRange libraryRange, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.Commands.SourceRepositoryDependencyProvider.<>c__DisplayClass19_0.<<FindLibraryAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at NuGet.Commands.SourceRepositoryDependencyProvider.FindLibraryAsync(LibraryRange libraryRange, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.DependencyResolver.ResolverUtility.<>c__DisplayClass9_1.<<FindLibraryFromSourcesAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at NuGet.DependencyResolver.ResolverUtility.FindLibraryFromSourcesAsync(LibraryRange libraryRange, IEnumerable`1 providers, Func`2 action)
at NuGet.DependencyResolver.ResolverUtility.FindLibraryByVersionAsync(LibraryRange libraryRange, NuGetFramework framework, IEnumerable`1 providers, SourceCacheContext cacheContext, ILogger logger, CancellationToken token)
at NuGet.DependencyResolver.ResolverUtility.FindPackageLibraryMatchAsync(LibraryRange libraryRange, NuGetFramework framework, IEnumerable`1 remoteProviders, IEnumerable`1 localProviders, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.DependencyResolver.ResolverUtility.FindLibraryMatchAsync(LibraryRange libraryRange, NuGetFramework framework, String runtimeIdentifier, IEnumerable`1 remoteProviders, IEnumerable`1 localProviders, IEnumerable`1 projectProviders, IDictionary`2 lockFileLibraries, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.DependencyResolver.ResolverUtility.FindLibraryEntryAsync(LibraryRange libraryRange, NuGetFramework framework, String runtimeIdentifier, RemoteWalkContext context, CancellationToken cancellationToken)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge, TransitiveCentralPackageVersions transitiveCentralPackageVersions)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge, TransitiveCentralPackageVersions transitiveCentralPackageVersions)
at NuGet.DependencyResolver.RemoteDependencyWalker.WalkAsync(LibraryRange library, NuGetFramework framework, String runtimeIdentifier, RuntimeGraph runtimeGraph, Boolean recursive)
at NuGet.Commands.ProjectRestoreCommand.WalkDependenciesAsync(LibraryRange projectRange, NuGetFramework framework, String runtimeIdentifier, RuntimeGraph runtimeGraph, RemoteDependencyWalker walker, RemoteWalkContext context, CancellationToken token)
at NuGet.Commands.ProjectRestoreCommand.TryRestoreAsync(LibraryRange projectRange, IEnumerable`1 frameworkRuntimePairs, NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteDependencyWalker remoteWalker, RemoteWalkContext context, Boolean forceRuntimeGraphCreation, CancellationToken token, TelemetryActivity telemetryActivity)
at NuGet.Commands.RestoreCommand.ExecuteRestoreAsync(NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteWalkContext context, CancellationToken token, TelemetryActivity telemetryActivity)
at NuGet.Commands.RestoreCommand.ExecuteAsync(CancellationToken token)
at NuGet.Commands.RestoreRunner.ExecuteAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
at NuGet.Commands.RestoreRunner.ExecuteAndCommitAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
at NuGet.Commands.RestoreRunner.CompleteTaskAsync(List`1 restoreTasks)
at NuGet.Commands.RestoreRunner.RunAsync(IEnumerable`1 restoreRequests, RestoreArgs restoreContext, CancellationToken token)
at NuGet.Commands.RestoreRunner.RunAsync(RestoreArgs restoreContext, CancellationToken token)
at NuGet.Build.Tasks.BuildTasksUtility.RestoreAsync(DependencyGraphSpec dependencyGraphSpec, Boolean interactive, Boolean recursive, Boolean noCache, Boolean ignoreFailedSources, Boolean disableParallel, Boolean force, Boolean forceEvaluate, Boolean hideWarningsAndErrors, Boolean restorePC, Boolean cleanupAssetsForUnsupportedProjects, ILogger log, CancellationToken cancellationToken)
at NuGet.Build.Tasks.RestoreTask.ExecuteAsync(ILogger log)
Done executing task "RestoreTask" -- FAILED.
1>Done building target "Restore" in project "MySolution.sln" -- FAILED.
1>Done Building Project "/home/vsts/work/1/s/MySolution/MySolution.sln" (Restore target(s)) -- FAILED.
Build FAILED.
"/home/vsts/work/1/s/MySolution/MySolution.sln" (Restore target) (1) ->
(Restore target) ->
My first thoughts were the same as anyone elses... AH the path must be incorrect! However... I cannot seem to get it to work after trying various different paths to get to the packages folder to pick up my local NuGet package.
To assist, my config files are below.
azure-pipelines.yml:
trigger:
- master
pool:
vmImage: 'ubuntu-latest'
variables:
buildConfiguration: 'Release'
steps:
- task: NuGetToolInstaller#1
displayName: 'Use NuGet 4.9.1'
inputs:
versionSpec: 4.9.1
- task: DotNetCoreCLI#2
displayName: 'Restore NuGet Packages'
inputs:
command: 'restore'
projects: '**/*.sln'
feedsToUse: 'config'
nugetConfigPath: 'MySolution/NuGet.Config'
- task: DotNetCoreCLI#2
displayName: 'Build web project'
inputs:
command: 'build'
projects: $(SolutionPath)
NuGet.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="LocalPackages" value="MySolution/packages" />
</packageSources>
</configuration>
The part in question I have been messing about with is the "LocalPackages" element which is where I thought the issue could be, so have been trying all sorts of combinations of paths to try and narrow it down - but no luck - which has made me think this could be a red herring, but you never know I could be doing something stupid!
I understand there are best practices which can be followed here such as creating my own Artifacts feed of NuGet packages for maintainability, but this is going to be a refinement phase later for me, my focus at the moment is just to simply get the pipeline in a build state ready for deployment and testing.
Any help or guidance on this or things I can try to fix this would be greatly appreciated!
Let me know if more specific info is needed and I can provide!
Thank you.
It is the local packages path that causes the problem. You should set the value as <add key="LocalPackages" value="../s/MySolution/packages" />
If you check the dotnet restore task log, you will find a temp config was created, And the restore task was using this temp config file. See below.
So the LocalPackages path you specified in nuget.config file is relative to the temp config folder /home/vsts/work/1/Nuget.
Since your project is cloned in folder /home/vsts/work/1/s (ie. $(system.defaultworkingdirectory)). You should specify the LocalPackages path like below:
<add key="LocalPackages" value="../s/MySolution/packages" />

"Exception has been thrown by the target of an invocation" error when injecting Amazon S3 Service in ASP .Net Core constructor

I have an ASP .Net Core 2.2 Web API. In it, I have an endpoint where the front-end (Angular app) can send a file to the API, and the API in turn uploads this file to an Amazon S3 bucket (us-east-1 region).
This works perfectly while I'm debugging in Visual Studio, but when I publish to my server (Windows Server 2016) I get the following exception:
Error: Exception has been thrown by the target of an
invocation. at System.RuntimeMethodHandle.InvokeMethod(Object
target, Object[] arguments, Signature sig, Boolean constructor,
Boolean wrapExceptions) at
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags
invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Amazon.Extensions.NETCore.Setup.ClientFactory.CreateClient(Type
serviceInterfaceType, AWSCredentials credentials, ClientConfig config)
at
Amazon.Extensions.NETCore.Setup.ClientFactory.CreateServiceClient(ILogger
logger, Type serviceInterfaceType, AWSOptions options) at
Amazon.Extensions.NETCore.Setup.ClientFactory.CreateServiceClient(IServiceProvider
provider) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite
factoryCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite
scopedCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite
singletonCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite
constructorCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite
scopedCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite
singletonCallSite, ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(IServiceCallSite
callSite, TArgument argument) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.
b__0(ServiceProviderEngineScope scope) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type
serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type
serviceType) at
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider
sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] ) at
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.
b__0(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.
g__CreateController|0(ControllerContext
controllerContext) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State&
next, Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext
context) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next,
Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext
httpContext) at
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext
httpContext) at
PropWorx.API.Middlewares.TenantIdentifier.Invoke(HttpContext
httpContext, SharedContext sharedContext) in
C:\Users\fabsr\source\repos\PropWorx.API\PropWorx.API\Middlewares\TenantIdentifier.cs:line
73 at
Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext
context) at
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext
httpContext) at
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext
httpContext, ISwaggerProvider swaggerProvider) at
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext
context) at
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext
context)
I've created the "credentials" file in the %UserProfile%.aws folder.
I've added the following two NuGet packages to the project:
AWSSDK.Extensions.NETCore.Setup
AWSSDK.S3
I have this in my Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAWSService<IAmazonS3>();
services.AddSingleton<IS3Service, S3Service>();
}
S3Service.cs looks like this:
public class S3Service : IS3Service
{
private readonly IAmazonS3 _client;
public S3Service(IAmazonS3 client)
{
_client = client;
}
// Some methods to upload and delete objects... not important
}
I inject this service to one of my controllers:
public class FilesController : ControllerBase
{
private readonly IS3Service _s3Service;
public FilesController(IS3Service s3Service)
{
_s3Service = s3Service;
}
// Some actions to receive the file... not important
}
The error happens as soon as I call any action in this controller. In fact, the error appears to be happening when the S3Service is injected into the controller's constructor. If I remove the constructor injection, i.e.:
public class FilesController : ControllerBase
{
private readonly IS3Service _s3Service;
public FilesController()
{
}
// Some actions to receive the file... not important
}
The error goes away (but of course doesn't work properly)
Any ideas? Like I said, this works perfectly on my laptop while debugging in VS2017. But it doesn't work when published to the server. All other controllers in the API work fine. It appears to be a problem at the point of injecting the S3Service in the constructor...
I kept it simple. In my local machines, I was keeping the keys in the user-secrets and on the prod server I was keeping those in the IIS configuration file. and was just accessing these values from ConfigurationManager. Basically it was using the new AmazonS3Client(string, string, string) syntax. Also I was using a farily older version of .net core there is a possibility that the issue was fixed. Check out this which seems working.
I changed my code to get IAmazonS3 insatance not through but directly instantiating it inside my IS3Serice method and it worked. Somehow the DI is not able to pick config values and that's why was not able to resolve the object.
You can get some information about this from here
I went through the actual documentation
https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-netcore.html
and found following:
If you look at the Debug tab in your project's properties, you can see this file is set to Development. This works great for local testing because you can put your configuration in the appsettings.Development.json file, which is read-only during local testing. When you deploy an Amazon EC2 instance that has EnvironmentName set to Production, this file is ignored and the AWS SDK for .NET falls back to the IAM credentials and region configured for the Amazon EC2 instance.
So this could be the reason that your initial configurations didn't work as you were trying to use access keys on production.
Also have a look at following answer
How to set credentials on AWS SDK on NET Core?

ASP NET Core 2 Cannot find compilation library location for package 'Projectname.Model'

In my solution, I have two projects. One of them is web project and the other one is Model project. You can see my solution structure in below:
Now when I run application I get the following error:
InvalidOperationException: Cannot find compilation library location for package 'ContosoUniversity.Model'
And here is full stack trace :
An unhandled exception occurred while processing the request.
InvalidOperationException: Cannot find compilation library location for package 'ContosoUniversity.Model'
Microsoft.Extensions.DependencyModel.CompilationLibrary.ResolveReferencePaths(ICompilationAssemblyResolver resolver, List<string> assemblies)
InvalidOperationException: Cannot find compilation library location for package 'ContosoUniversity.Model'
Microsoft.Extensions.DependencyModel.CompilationLibrary.ResolveReferencePaths(ICompilationAssemblyResolver resolver, List<string> assemblies)
Microsoft.Extensions.DependencyModel.CompilationLibrary.ResolveReferencePaths()
Microsoft.AspNetCore.Mvc.ApplicationParts.AssemblyPart+<>c.<GetReferencePaths>b__8_0(CompilationLibrary library)
System.Linq.Enumerable+SelectManySingleSelectorIterator.MoveNext()
Microsoft.AspNetCore.Mvc.Razor.Compilation.MetadataReferenceFeatureProvider.PopulateFeature(IEnumerable<ApplicationPart> parts, MetadataReferenceFeature feature)
Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature<TFeature>(TFeature feature)
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorReferenceManager.GetCompilationReferences()
System.Threading.LazyInitializer.EnsureInitializedCore<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorReferenceManager.get_CompilationReferences()
Microsoft.AspNetCore.Mvc.Razor.Internal.LazyMetadataReferenceFeature.get_References()
Microsoft.CodeAnalysis.Razor.CompilationTagHelperFeature.GetDescriptors()
Microsoft.AspNetCore.Razor.Language.DefaultRazorTagHelperBinderPhase.ExecuteCore(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Razor.Language.RazorEnginePhaseBase.Execute(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Razor.Language.DefaultRazorEngine.Process(RazorCodeDocument document)
Microsoft.AspNetCore.Razor.Language.RazorTemplateEngine.GenerateCode(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(string relativePath)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CreateCacheEntry(string normalizedPath)
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(string relativePath)
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet<IChangeToken> expirationTokens, string relativePath, bool isMainPage)
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey)
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, string pageName, bool isMainPage)
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, string viewName, bool isMainPage)
Microsoft.AspNetCore.Mvc.ViewEngines.CompositeViewEngine.FindView(ActionContext context, string viewName, bool isMainPage)
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor.FindView(ActionContext actionContext, ViewResult viewResult)
Microsoft.AspNetCore.Mvc.ViewResult+<ExecuteResultAsync>d__26.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeResultAsync>d__19.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResultFilterAsync>d__24.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeFilterPipelineAsync>d__17.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeAsync>d__15.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()
I use ASP NET Core 2 and VS17.
Here is my ContosoUniversity.csproj file if you need it:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="ContosoUniversity.Model">
<HintPath>..\ContosoUniversity.Model\bin\Debug\netcoreapp2.0\ContosoUniversity.Model.dll</HintPath>
</Reference>
</ItemGroup>
</Project>
What should I do to solve this problem?
In order asp.net core 2.0 project had successfully found external assemblies .NETStandard2.0, you need to override a built-in MetadataReferenceFeatureProvider. For this we need to add the following class:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection.PortableExecutable;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyModel;
namespace Microsoft.AspNetCore.Mvc.Razor.Compilation
{
/// <summary>Провайдер нужен для компенсации бага компиляции представлений при подключении сборок .NetStandart2.0</summary>
public class ReferencesMetadataReferenceFeatureProvider : IApplicationFeatureProvider<MetadataReferenceFeature>
{
public void PopulateFeature(IEnumerable<ApplicationPart> parts, MetadataReferenceFeature feature)
{
var libraryPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var assemblyPart in parts.OfType<AssemblyPart>())
{
var dependencyContext = DependencyContext.Load(assemblyPart.Assembly);
if (dependencyContext != null)
{
foreach (var library in dependencyContext.CompileLibraries)
{
if (string.Equals("reference", library.Type, StringComparison.OrdinalIgnoreCase))
{
foreach (var libraryAssembly in library.Assemblies)
{
libraryPaths.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, libraryAssembly));
}
}
else
{
foreach (var path in library.ResolveReferencePaths())
{
libraryPaths.Add(path);
}
}
}
}
else
{
libraryPaths.Add(assemblyPart.Assembly.Location);
}
}
foreach (var path in libraryPaths)
{
feature.MetadataReferences.Add(CreateMetadataReference(path));
}
}
private static MetadataReference CreateMetadataReference(string path)
{
using (var stream = File.OpenRead(path))
{
var moduleMetadata = ModuleMetadata.CreateFromStream(stream, PEStreamOptions.PrefetchMetadata);
var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata);
return assemblyMetadata.GetReference(filePath: path);
}
}
}
}
And also replace in your Startup "services.AddMvc()" with the following code:
services.AddMvc() // Следующий патч нужен для компенсации бага компиляции представлений при подключении сборок .NetStandart2.0
.ConfigureApplicationPartManager(manager =>
{
manager.FeatureProviders.Remove(manager.FeatureProviders.First(f => f is MetadataReferenceFeatureProvider));
manager.FeatureProviders.Add(new ReferencesMetadataReferenceFeatureProvider());
});
If your app is compiling Razor code in runtime and you are in .netcore2+ it seems you need to add this to your project:
<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
This copies the refs folder on publish - it is large - but it seems to be needed
For resolve this problem you should inject IServiceProvider in Startup constructor like this:
public Startup(IConfiguration configuration, IHostingEnvironment env, IServiceProvider serviceProvider)
{
Configuration = configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
var mvcBuilder = serviceProvider.GetService<IMvcBuilder>();
new MvcConfiguration().ConfigureMvc(mvcBuilder);
Configuration = builder.Build();
}
It's likely that you are publishing the app without reference assemblies. Try setting
<CopyRefAssembliesToPublishDirectory>true</CopyRefAssembliesToPublishDirectory>
in your app's project file.
For me I needed to choose "Remove additional files at destination" in the publish profile for this to resolve. Another member of our dev team had recently published from their machine which may have factored in.
Be careful with your project however - if you have assets on the server you don't have locally, they will get deleted (user uploaded content for example).
I solved this issue after many attempts.
You just need to change your .csproj and switch
<Project Sdk="Microsoft.NET.Sdk">
with
<Project Sdk="Microsoft.NET.Sdk.Razor">
I have added few other lines in the csproj, but I believe this is the only one that is required.
Also I had to clean the previously generated files before publishing.

Why won't my MVC4 HandleErrorAttribute work?

I'm converting an MVC3 web project to MVC4. I created a ElmahHandleErrorAttribute that inherits from HandleErrorAttribute that worked fine in MVC3 and also works fine on my local dev machine, but it throws the following exception in the test environment...
[InvalidOperationException: The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.]
System.Web.Mvc.GlobalFilterCollection.ValidateFilterInstance(Object instance) +110
System.Web.Mvc.GlobalFilterCollection.AddInternal(Object filter, Nullable`1 order) +17
System.Web.Mvc.GlobalFilterCollection.Add(Object filter) +12
Home2Me.MvcApplication.RegisterGlobalFilters(GlobalFilterCollection filters) in c:\###\Home2Me\Global.asax.cs:16
Home2Me.MvcApplication.Application_Start() in c:\###\Home2Me\Global.asax.cs:118
[HttpException (0x80004005): The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9249709
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +131
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +194
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +339
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +253
[HttpException (0x80004005): The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9164336
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +256
There isn't really anything special about the class. It's pretty close to the standard one for Elmah.
public class ElmahHandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
/// <summary>
/// Called when an exception occurs.
/// </summary>
/// <param name="context"></param>
public override void OnException(ExceptionContext context)
{
base.OnException(context);
if (!context.ExceptionHandled) return; // if unhandled, will be logged anyhow
var e = context.Exception;
HandleException(e);
}
... (code snipped for brevity) ...
}
And here is the code that registers the filter in Global.asax.cs...
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ElmahHandleErrorAttribute());
}
The filter is defined in a separate assembly that is also updated to MVC4. I have multiple projects that use this filter. One of them works fine in the test environment, and another has this same exact issue.
Any ideas on what might be wrong? I'm fairly confident that all the MVC3 references have been updated correctly in the project, including the web.config files in both the root and views directory. It does work locally and I uninstalled MVC3 and deleted all the "extra" MVC3 dlls lying around.
I believe I found an answer. I added a runtime section in the root web.config file to convert MVC3 references to MVC4.
<configuration>
... (snipped for brevity) ...
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I would rather fix whatever it is that is referencing MVC3, but I can't figure out what that might be. This will have to be a good enough answer for now.