Import method of windows security encryption algorithm is not working in hosting environment - asp.net-core

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?

Related

datatable.net-bs5 issue after migrating to abp v5.0 and .net 6.0

I am stuck here i have tried installing this 'datatables.net-bs5' package through nuget and npm but nothing worked
An exception was thrown attempting to execute the error handler.
Volo.Abp.AbpException: Could not find the bundle file '/libs/datatables.net-bs5/css/dataTables.bootstrap5.css' for the bundle 'Basic.Global'!
at Volo.Abp.AspNetCore.Mvc.UI.Bundling.TagHelpers.AbpTagHelperResourceService.ProcessAsync(ViewContext viewContext, TagHelper tagHelper, TagHelperContext context, TagHelperOutput output, List`1 bundleItems, String bundleName)
at Volo.Abp.AspNetCore.Mvc.UI.Bundling.TagHelpers.AbpBundleTagHelperService`2.ProcessAsync(TagHelperContext context, TagHelperOutput output)
at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, Int32 i, Int32 count)
at AspNetCore.Pages_Shared__Layout.<>c__DisplayClass13_0.<<ExecuteAsync>b__0>d.MoveNext() in E:\Work\FinancialsAe\FinancialsAce\src\FinancialsAce.Blazor.Server\Pages\Shared\_Layout.cshtml:line 45
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
at AspNetCore.Pages_Shared__Layout.ExecuteAsync() in E:\Work\FinancialsAe\FinancialsAce\src\FinancialsAce.Blazor.Server\Pages\Shared\_Layout.cshtml:line 27
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderLayoutAsync(ViewContext context, ViewBufferTextWriter bodyWriter)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|22_0(ResourceInvoker invoker, IActionResult result)
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()
Running following command in project directory resolved the issue
"abp install-libs"

Dot net core API failing with Unable to cast object of type 'System.String' to type 'System.Int64'

I am calling a .Net Core 3.1 Web API and getting the error:
Unable to cast object of type 'System.String' to type 'System.Int64'.
RequestPath: /fulfillment/api/v1/orderitems/12579618/isuseinreport/true/orderitementities
SpanId: |4b43f9c5-4a4b193f28fac198.
TraceId: 4b43f9c5-4a4b193f28fac198
ParentId:
Connection ID "17149707382637556404", Request ID "800172b6-0000-ee00-b63f-84710c7967bb": An unhandled exception was thrown by the application.
Exception:
System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int64'.
at HistOrderAPI.Controllers.OrderItemEntitiesController.ListOrderItemEntitiesByOrderItemID(Int64 InOID, Nullable`1 InIsUseInReport)
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
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.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
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.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Builder.Extensions.UsePathBaseMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()
The value being converted in the URL is 12579618 and should not be a problem for Int64.

InvalidSaml2BindingException: Not HTTP GET Method

I am using ITfoxtec.Identity.Saml2.MvcCore 4.0.7 with TestWebAppCore and TestIdPCore from GitHub ITfoxtec.
When I run this sample from Visual Studio I am not getting any errors and everything works fine. But when I deploy these samples to IIS 10 on Windows server 2019 then I get an error on testing SecurePage, see my error here below.
It looks like ITfoxtec.Identity.Saml2.Saml2RedirectBinding.Read method receives an POST request in the Sample program instead of GET.
Can you help me with this exception?
An unhandled exception occurred while processing the request.
InvalidSaml2BindingException: Not HTTP GET Method.
ITfoxtec.Identity.Saml2.Saml2RedirectBinding.Read(HttpRequest request, Saml2Request saml2RequestResponse, string messageName, bool validateXmlSignature) in Saml2RedirectBinding.cs, line 151
Stack Query Cookies Headers Routing
InvalidSaml2BindingException: Not HTTP GET Method.
ITfoxtec.Identity.Saml2.Saml2RedirectBinding.Read(HttpRequest request, Saml2Request saml2RequestResponse, string messageName, bool validateXmlSignature) in Saml2RedirectBinding.cs
throw new InvalidSaml2BindingException("Not HTTP GET Method.");
ITfoxtec.Identity.Saml2.Saml2Binding.ReadSamlRequest(HttpRequest request, Saml2Request saml2Request) in Saml2Binding.cs
{
TestIdPCore.Controllers.AuthController.ReadRelyingPartyFromLoginRequest(Saml2Binding binding) in AuthController.cs
return binding.ReadSamlRequest(Request.ToGenericHttpRequest(), new Saml2AuthnRequest(config))?.Issuer;
TestIdPCore.Controllers.AuthController.Login() in AuthController.cs
var relyingParty = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding));
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
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)
Kind Regards
Ed
I have not seen this error before I'm afraid. It looks like the SAML 2.0 Authn Request is send as POST instead of GET.
The samples for ITfoxtec Identity SAML handels SAML 2.0 Authn Request with Saml2RedirectBinding by default. Do the TestWebAppCore.AuthController Login method in your case use Saml2RedirectBinding?

InvalidOperationException: Unable to resolve service for type '*Models.LandingPageContext' while attempting to activate Controller'

I have a database named "LandingPage", and using this command i have mapped the database tables inside my asp.net mvc core:-
Scaffold-DbContext "Server=(localdb)\ProjectsV13;Database=LandingPage;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Then i added a controller and chose one of the models, but when i try access the controller i got this exception inside the web browser:-
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'LandingPage.Models.LandingPageContext' while attempting to activate 'LandingPage.Controllers.QuestionsController'.
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 'LandingPage.Models.LandingPageContext' while attempting to activate 'LandingPage.Controllers.QuestionsController'.
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.<CreateActivator>b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass5_0.<CreateControllerFactory>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.<InvokeNextResourceFilter>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.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
The DbContext needs to be registered as a service in Startup.cs so that it can be injected into the controller in its constructor:
Startup.cs:
services.AddDbContext<LandingPageContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
QuestionsController.cs:
public class QuestionsController: Controller
{
public QuestionsController(LandingPageContext dbContext)
{
}
}
More information in Dependency injection in ASP.NET Core.

"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?