Autofac DependencyResolutionException - asp.net-core

I am getting following error:
Autofac.Core.DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor(System.String, Int32)' on type 'AerospikeClient'.
Following is the stacktrace of autofac:
at Autofac.Core.Activators.Reflection.BoundConstructor.Instantiate()
at
Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext
context, IEnumerable1 parameters) at Autofac.Core.Activators.Reflection.ReflectionActivator.<ConfigurePipeline>b__11_0(ResolveRequestContext ctxt, Action1 next) at
Autofac.Core.Resolving.Middleware.DelegateMiddleware.Execute(ResolveRequestContext
context, Action1 next) at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt) at Autofac.Core.Resolving.Middleware.DisposalTrackingMiddleware.Execute(ResolveRequestContext context, Action1 next) at
Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.b__1(ResolveRequestContext
ctxt) at
Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext
context, Action1 next) --- End of inner exception stack trace --- at Autofac.Core.Resolving.Middleware.ActivatorErrorHandlingMiddleware.Execute(ResolveRequestContext context, Action1 next) at
Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.b__1(ResolveRequestContext
ctxt) at
Autofac.Core.Pipeline.ResolvePipeline.Invoke(ResolveRequestContext
ctxt) at
Autofac.Core.Resolving.Middleware.RegistrationPipelineInvokeMiddleware.Execute(ResolveRequestContext
context, Action1 next) at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt) at Autofac.Core.Resolving.Middleware.SharingMiddleware.Execute(ResolveRequestContext context, Action1 next) at
Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.b__1(ResolveRequestContext
ctxt) at
Autofac.Core.Resolving.Middleware.ScopeSelectionMiddleware.Execute(ResolveRequestContext
context, Action1 next) at Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.<BuildPipeline>b__1(ResolveRequestContext ctxt) at Autofac.Core.Resolving.Middleware.CircularDependencyDetectorMiddleware.Execute(ResolveRequestContext context, Action1 next) at
Autofac.Core.Resolving.Pipeline.ResolvePipelineBuilder.<>c__DisplayClass14_0.b__1(ResolveRequestContext
ctxt) at
Autofac.Core.Pipeline.ResolvePipeline.Invoke(ResolveRequestContext
ctxt) at
Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope
currentOperationScope, ResolveRequest request) at
Autofac.Core.Resolving.ResolveOperation.ExecuteOperation(ResolveRequest
request) at
Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest
request) at
Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(ResolveRequest
request) at
Autofac.ResolutionExtensions.TryResolveService(IComponentContext
context, Service service, IEnumerable1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable1 parameters) at
Autofac.ResolutionExtensions.ResolveOptional(IComponentContext
context, Type serviceType, IEnumerable`1 parameters) at
Autofac.ResolutionExtensions.ResolveOptional(IComponentContext
context, Type serviceType) at
Autofac.Extensions.DependencyInjection.AutofacServiceProvider.GetService(Type
serviceType) at
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider
sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
Following is my registration:
builder.RegisterType<AerospikeClient>().As<IAerospikeClient>()
.WithParameter("hostname", _configuration["AerospikeHostName"])
.WithParameter("port", int.Parse(_configuration["AerospikePort"]))
.SingleInstance();
_configuration is getting passed to my autofac module and it is of type IConfigurationRoot. I am doing this so that I can pass values from outside.
If I change the above registration to:
builder.RegisterType<AerospikeClient>().As<IAerospikeClient>()
.WithParameter("hostname", "172.27.159.44")
.WithParameter("port", 3000)
.SingleInstance();
then it starts working. However I don't want to hardcode my values like that. Then I lose my chance of overriding them based on different environments.
What am I doing wrong here?

Check the actual type returned from _configuration["AerospikeHostName"]. Is it actually string, or is it something that happens to be assignable to string?
Equally, check the actual value used is valid, because Autofac should be fine expecting that string value.
Also, in future, consider using the built-in diagnostics to get a clearer picture of what exceptions are being thrown during resolve operations.

Related

Sign Up/In not working in ASP. NET Core application: Azure B2C

We configured user flow with Google as identity provider. Followed the Azure-Sample repository on GitHub in building one ASP.NET Core webapp with .NET6.
appsettings.json:-
"AzureAdB2C": {
"Instance": "https://b2ctenant.b2clogin.com",
"ClientId": "3ae27e38-90a3-43c7-9bac-8d3bf33227f9",
"Domain": "b2ctenant.b2clogin.com",
"SignedOutCallbackPath": "/signout/B2C_1_susi",
"SignUpSignInPolicyId": "b2c_1_susi",
"ResetPasswordPolicyId": "b2c_1_reset",
"EditProfilePolicyId": "b2c_1_edit_profile" // Optional profile editing policy
//"CallbackPath": "/signin/B2C_1_sign_up_in" // defaults to /signin-oidc
https://localhost:44316
Getting exception when users select Sign Up/In option
IOException: IDX20807: Unable to retrieve document from: '[PII of type 'System.String' is hidden. For more details, see
https://aka.ms/IdentityModel/PII.]'. HttpResponseMessage: '[PII of
type 'System.Net.Http.HttpResponseMessage' is hidden. For more
details, see https://aka.ms/IdentityModel/PII.]',
HttpResponseMessage.Content: '[PII of type 'System.String' is hidden.
For more details, see https://aka.ms/IdentityModel/PII.]'.
Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string
address, CancellationToken cancel)
Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(string
address, IDocumentRetriever retriever, CancellationToken cancel)
Microsoft.IdentityModel.Protocols.ConfigurationManager.GetConfigurationAsync(CancellationToken
cancel)
nvalidOperationException: IDX20803: Unable to obtain configuration from: '[PII of type 'System.String' is hidden. For more
details, see https://aka.ms/IdentityModel/PII.]'.
Microsoft.IdentityModel.Protocols.ConfigurationManager.GetConfigurationAsync(CancellationToken
cancel)
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleChallengeAsyncInternal(AuthenticationProperties
properties)
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.HandleChallengeAsync(AuthenticationProperties
properties)
Microsoft.AspNetCore.Authentication.AuthenticationHandler.ChallengeAsync(AuthenticationProperties
properties)
Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext
context, string scheme, AuthenticationProperties properties)
Microsoft.AspNetCore.Mvc.ChallengeResult.ExecuteResultAsync(ActionContext
context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|30_0<TFilter,
TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next,
Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed
context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter,
TFilterAsync>(ref State next, ref Scope scope, ref object state, ref
bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|28_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, object state, bool
isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_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.g__Awaited|20_0(ResourceInvoker
invoker, Task lastTask, State next, Scope scope, object state, bool
isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker
invoker)
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.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext
context)
I tried to reproduce the same in my environment and got below results:
I registered one application and granted API permissions like below:
I cloned the same GitHub sample and updated appsettings.json file same as you like below:
I ran the above sample and got below screen:
When I clicked on Sign Up/In button, I got same error as you like below:
Note that, you are giving wrong value to your Domain parameter in your appsettings.json file. You need to change value of Domain parameter that can be found here:
To resolve the error, I changed value of Domain parameter in my
appsettings.json file like below:
When I clicked on Sign Up/In button now by running the sample, I got the login screen with Google successfully like below:
Reference: Configure authentication using Azure Active Directory B2C | Microsoft

OData grouping entities

I'm trying to have the following urls
v1/$metadata
v1/se/companies
v1/se/addresses
v1/no/companies
v1/no/addresses
But if i use [ODataRoutePrefix("se/Companies")] i get the following error
System.InvalidOperationException: The path template 'se/Companies({companyNumber})' on the action 'Get' in controller 'SwedishCompany' is not a valid OData path template. Resource not found for the segment 'se'.
at Microsoft.AspNet.OData.Routing.Conventions.AttributeRoutingConvention.GetODataPathTemplate(String prefix, String pathTemplate, IServiceProvider requestContainer, String controllerName, String actionName)
at Microsoft.AspNet.OData.Routing.Conventions.AttributeRoutingConvention.<>c__DisplayClass11_0.<GetODataPathTemplates>b__1(ODataRouteAttribute route)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at Microsoft.AspNet.OData.Routing.Conventions.AttributeRoutingConvention.BuildAttributeMappings(IEnumerable`1 controllerActions)
at Microsoft.AspNet.OData.Routing.Conventions.AttributeRoutingConvention.get_AttributeMappings()
at Microsoft.AspNet.OData.Routing.Conventions.AttributeRoutingConvention.SelectAction(RouteContext routeContext)
at Microsoft.AspNet.OData.Routing.ODataActionSelector.SelectCandidates(RouteContext context)
at Microsoft.AspNetCore.Mvc.Internal.MvcRouteHandler.RouteAsync(RouteContext context)
at Microsoft.AspNetCore.Routing.Route.OnRouteMatched(RouteContext context)
at Microsoft.AspNetCore.Routing.RouteBase.RouteAsync(RouteContext context)
at Microsoft.AspNetCore.Routing.RouteCollection.RouteAsync(RouteContext context)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
Is there some way to add a prefix with a /?

How to Solve Redis Multiplexer in ASP.NET Core Problem

I my dotnet core project i am using redis for caching. In work fine in local,but i am getting following error in ubuntu server
Error
StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketClosed on PING
at StackExchange.Redis.ConnectionMultiplexer.ConnectAsync(String configuration, TextWriter log) in c:\code\StackExchange.Redis\StackExchange.Redis\StackExchange\Redis\ConnectionMultiplexer.cs:line 799
at Microsoft.Extensions.Caching.Redis.RedisCache.ConnectAsync(CancellationToken token)
at Microsoft.Extensions.Caching.Redis.RedisCache.GetAndRefreshAsync(String key, Boolean getData, CancellationToken token)
at Microsoft.Extensions.Caching.Redis.RedisCache.RefreshAsync(String key, CancellationToken token)
at Microsoft.AspNetCore.Session.DistributedSession.CommitAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
Unhandled Exception: StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketClosed on PING
at StackExchange.Redis.ConnectionMultiplexer.ConnectAsync(String configuration, TextWriter log) in c:\code\StackExchange.Redis\StackExchange.Redis\StackExchange\Redis\ConnectionMultiplexer.cs:line 799
at Microsoft.Extensions.Caching.Redis.RedisCache.ConnectAsync(CancellationToken token)
at Microsoft.Extensions.Caching.Redis.RedisCache.SetAsync(String key, Byte[] value, DistributedCacheEntryOptions options, CancellationToken token)
at otpservice.Helper.HOtp.GenerateOtp(String userid) in D:\SampleHelper\HOtp.cs:line 39
at otpservice.Controllers.OtpController.Otp(Object userData) in D:\Sample\Controllers\OtpController.cs:line 41
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.ThreadPoolWorkQueue.Dispatch()
Aborted
ConfigureService method in Startup.cs
services.AddDistributedRedisCache(options =>
{
options.InstanceName = "Sample";
//For the Server i am using IP Instead of localhost
options.Configuration = "localhost";
});
During caching in my Code
var cache = new RedisCache(new RedisCacheOptions
{
//For the Server i am using IP Instead of localhost
Configuration = "localhost",
});
How to Solve the error.
Thank you...

ServiceFabric: Service does not exist during deployment

I have an existing system using service fabric. Everything is fine except during a service publish the service is unavailable and any resolutions return an error.
This is expected however it would be nice if during this time instead the calls just waited or timedout. During this time my error logs will sometimes fill up with 200K lines of the same error.
I want some code like the following however where would it go?
public async Task Execute(Func<Task> action)
{
try
{
action()
.ConfigureAwait(false);
}
catch (FabricServiceNotFoundException ex)
{
await Task.Delay(TimeSpan.FromSeconds(??))
.ConfigureAwait(false);
action()
.ConfigureAwait(false);
}
}
Error:
System.Fabric.FabricServiceNotFoundException: Service does not exist. ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80071BCD
at System.Fabric.Interop.NativeClient.IFabricServiceManagementClient6.EndResolveServicePartition(IFabricAsyncOperationContext context)
at System.Fabric.FabricClient.ServiceManagementClient.ResolveServicePartitionEndWrapper(IFabricAsyncOperationContext context)
at System.Fabric.Interop.AsyncCallOutAdapter2`1.Finish(IFabricAsyncOperationContext context, Boolean expectedCompletedSynchronously)
--- End of inner exception stack trace ---
at Microsoft.ServiceFabric.Services.Client.ServicePartitionResolver.ResolveHelperAsync(Func`5 resolveFunc, ResolvedServicePartition previousRsp, TimeSpan resolveTimeout, TimeSpan maxRetryInterval, CancellationToken cancellationToken, Uri serviceUri)
at Microsoft.ServiceFabric.Services.Communication.Client.CommunicationClientFactoryBase`1.CreateClientWithRetriesAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplicaSelector, String listenerName, OperationRetrySettings retrySettings, Boolean doInitialResolve, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Communication.Client.CommunicationClientFactoryBase`1.GetClientAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplica, String listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.V2.FabricTransport.Client.FabricTransportServiceRemotingClientFactory.GetClientAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplicaSelector, String listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Communication.Client.ServicePartitionClient`1.GetCommunicationClientAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Communication.Client.ServicePartitionClient`1.InvokeWithRetryAsync[TResult](Func`2 func, CancellationToken cancellationToken, Type[] doNotRetryExceptionTypes)
at Microsoft.ServiceFabric.Services.Remoting.V2.Client.ServiceRemotingPartitionClient.InvokeAsync(IServiceRemotingRequestMessage remotingRequestMessage, String methodName, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.Builder.ProxyBase.InvokeAsyncV2(Int32 interfaceId, Int32 methodId, String methodName, IServiceRemotingRequestMessageBody requestMsgBodyValue, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.Builder.ProxyBase.ContinueWithResultV2[TRetval](Int32 interfaceId, Int32 methodId, Task`1 task)
As expected, Service Fabric have to shutdown the service to start the new version, this will cause a transient error like the one you've got.
By default, the Remoting APIs already have a retry logic built-in, from the docs:
The service proxy handles all failover exceptions for the service
partition it is created for. It re-resolves the endpoints if there are
failover exceptions (non-transient exceptions) and retries the call
with the correct endpoint. The number of retries for failover
exceptions is indefinite. If transient exceptions occur, the proxy
retries the call.
With that said, you should not require to add extra retry logic, maybe you should try adjust the OperationRetrySettings for a better handling of these retries.
If does not solve the problem, and you still want to add the logic in your code, the simplest way to handle it is using a transient-fault-handling library like Polly, something like below:
var policy = Policy
.Handle<FabricServiceNotFoundException>()
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(3)
});
policy.Execute(() => DoSomething());
In this sample, you do an exponential backoff between retries, if the number of calls is too big, I would recomend implement the circuit breaker approach instead.

MVC account controller error and LogOff not working

This is my first MVC project so I am learning a lot. Right now I am getting an error and I can't figure out where it's coming from. I took the default account controller and pointed it to my own sql database as shown below. I put the [Authorize] attribute on every controller so only the login page can be accessed. Once the user logs in, it will allow them to access all the pages just fine, but first it redirects to this error:
Error.
An error occurred while processing your request.
Also, after changing the account controller, the LogOff action stopped working. I changed it as shown below but it's still not working. Strangely, this error was not appearing yesterday. I am near the deadline on this project so any help would be greatly appreciated, thanks!
Here is the modified account controller code
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
using (ixdb_siNet_ConfigurationEntities userdb = new ixdb_siNet_ConfigurationEntities())
{
var objUser = userdb.ixoc_Users.FirstOrDefault(x => x.name == model.UserName && x.password == model.Password);
if (objUser != null)
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Dashboard");
}
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
//AuthenticationManager.SignOut();
Request.Cookies.Remove("UserId");
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Dashboard");
}
Here is the stack trace
Server Error in '/' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.] siNetWebApplication.Controllers.DashboardController.Index(String startDate, String endDate) in c:\Merlin\Customers\Weir\Git\siNetWebApplication\siNetWebApplication\Controllers\DashboardController.cs:29 lambda_method(Closure , ControllerBase , Object[] ) +178 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +241 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +38 System.Web.Mvc.Async.AsyncControllerActionInvoker.b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +11 System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +138 System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3c() +111 System.Web.Mvc.Async.<>c__DisplayClass45.b__3e() +452 System.Web.Mvc.Async.<>c__DisplayClass30.b__2f(IAsyncResult asyncResult) +15 System.Web.Mvc.Async.<>c__DisplayClass28.b__19() +37 System.Web.Mvc.Async.<>c__DisplayClass1e.b__1b(IAsyncResult asyncResult) +241 System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +111 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +19 System.Web.Mvc.MvcHandler.b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +51 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +111 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
You most likely aren't passing the anti forgery token to the LogOff action.
You've got the [ValidateAntiForgeryToken] attribute on the action so you need to pass this otherwise you will get an error. If you turn custom errors off as #sanjeev has mentioned you will probably see the error regarding the anti forgery token not being passed.
Add this to the form in your view
#Html.AntiForgeryToken()
You mentioned when you login you get "Error. An error occurred while processing your request." and then everything works fine. It seems "Error. An error occurred while processing your request." is from /Views/Shared/Error.cshtml page. Just make sure /Dashboard/Index is valid url for your application.
You need to turn off the custom errors in web.config to get the actual cause for that error. This will help you to resolve logoff issue too.
<system.web>
<customErrors mode="Off" />
</system.web>
Can you remove the async Task<ActionResult> and use ActionResult for login post method?