MVC account controller error and LogOff not working - sql

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?

Related

Autofac DependencyResolutionException

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.

SimpleInjector is throwing ThrowMissingInstanceProducerException when injecting delegates into services

I am converting my ASP.Net application from MC3 to MVC4. I have Simpleinjector code from old MVC3 days as below
WebContainer.Instance.Container.GetInstance<Func<HttpRequestBase>>();
Now this line of code is throwing exception in the new SimpleInjector version 2.8.0. My application is in .Net framework 4.0. Please advise on the stack trace below
Message: No registration for type Func could be found.
Exception type: SimpleInjector.ActivationException
Stack Trace:
at SimpleInjector.Container.ThrowMissingInstanceProducerException(Type serviceType)
at SimpleInjector.Container.GetInstance[TService]()
at Aon.Exchange.Web.UserControlBase..ctor()
at ASP.cmswebparts_aonexchange_help2_ascx..ctor()
at __ASP.FastObjectFactory_app_web_help2_ascx_f5d8491b_aknegnyf.Create_ASP_cmswebparts_aonexchange_help2_ascx()
at System.Web.UI.TemplateControl.LoadControl(IWebObjectFactory objectFactory, VirtualPath virtualPath, Type t, Object[] parameters)
at System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath)
at CMS.PortalControls.CMSWebPartZone.LoadWebPart(Control container, CMSWebPartZone zone, WebPartInstance part, Boolean reloadData, Boolean isVariant)
The code for WebContainer is listed as below
this.Container = new Container();
SimpleInjectorWebInitializer.Initialize();
this.Container.RegisterPackages(GetAssemblies());
this.Container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
this.Container.RegisterMvcIntegratedFilterProvider();
this.RegisterGlobalFilters();
//this.Container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(this.Container));
//this.VerifyPages();
The registration of this func is as below
container.RegisterPerWebRequest<Func<HttpRequestBase>>(() => () => new HttpRequestWrapper(HttpContext.Current.Request));

Visual Studio Express 2012 - Silverlight-Enabled WCF Service?

I just started a new Silverlight project with Visual Studio Express 2012 for Web.
I created a Silverlight-enabled WCF service to access a SQL Server database, with EF 5.
The problem I'm having is that the service doesn't seem to be able to return any entity retrieved from the database. A new entity or any old object is returned just fine, but when I try to return an entity from the context I get the following exception:
{System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassa.<EndGetResponse>b__9(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
--- End of inner exception stack trace ---
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.DataServiceClientChannel.EndGetAgency(IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.NewProj.DataSvcRef.DataService.EndGetAgency(IAsyncResult result)
at NewProj.DataSvcRef.DataServiceClient.OnEndGetAgency(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)}
The service method code couldn't be simpler:
[OperationContract]
public Contact GetContact(int aID)
{
Contact res = null;
using (var db = new OFBEntities())
{
try
{
res = db.Contacts.Find(aID);
}
catch (Exception ex)
{
res = null;
}
return res;
}
}
As I mentioned, if I return a newly created object (return new Contact(){ name="test contact};), or return a type that is not in context (say an integer for example), everything works fine.
Is this a limitation of the express version, or am I forgetting some settings? In the past I have created some Silverlight apps that consumed data services with VS 2010, Silverlight 4, and I don't remember having to set anything special, but maybe I just forgot that I did?
Any help is appreciated!
EDIT:
Could it have anything to do with DbContext and the way it is serialized? I've never used DbContext before, I always used the default ObjectContext in EF 4...
EDIT2: SOLUTION
It's been a while, but I had other things to work :o)
In case anybody is in the same boat, the problem was in the serialization by the service. DbContext by default creates proxies, which don't agree with serialization. I am not sure why yet - indeed, I need to educate myself about those proxies - but disabling them solves my serialization issue.
Thanks for the comment Pawel, I mistakenly thought my serialization was going OK, rechecking the server-side error put me back on the right track.
The problem was with automatic proxy creation by the DBContext, which interfered with the serialization.
Proxies are on by default in DBContext, you can disable them in the class constructor
this.Configuration.ProxyCreationEnabled = false;
or after creating an instance of your DBContext
using (var db = new myDBContext())
{
db.Configuration.ProxyCreationEnabled = false;
...
}
Not sure why yet, but it works. Time to go read up on that!

ServiceStack Authenticate attribute results in null ref exception - pull request 267

I am making an MVC3 site using ServiceStacks authentication mechanism. When I add the AuthenticateAttribute to a controller, I get a null reference exception:
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=ServiceStack.FluentValidation.Mvc3
StackTrace:
at ServiceStack.Mvc.ExecuteServiceStackFiltersAttribute.OnActionExecuting(ActionExecutingContext filterContext) in C:\src\ServiceStack\src\ServiceStack.FluentValidation.Mvc3\Mvc\ExecuteServiceStackFiltersAttribute.cs:line 21
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
I can see in github that pull request #267 seems to make some null ref check exactly where my code currently throws. I have another project where authentication works, but the new failing code is running on a newer version of ServiceStack and I can't see what the difference is, so any ideas about what could cause this exception for new versions of service stack (v. 3.9.18)
Here is my configuration code:
Plugins.Add(new AuthFeature(
() => new AuthUserSession(), // Here a custom IAuthSession implementation could be used instead of UserSession.
// Allow authentication by using cookies set when authenticating with username/password credentials posted to the /auth/credentials service.
new IAuthProvider[]{ new CredentialsAuthProvider() }
)
);
//Enable Funq IOC in MVC controllers.
ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
IUserAuthRepository userRepository = new OrmLiteAuthRepository(dbFactory);
container.Register(userRepository);
container.Register<ICacheClient>(new MemoryCacheClient());
// Initialise Registration feature, providing the /register route.
Plugins.Add(new RegistrationFeature());
And my Controller base class:
public abstract class ControllerBase : ServiceStackController<AuthUserSession> {
public IDbConnectionFactory Db { get; set; }
public ILog Log { get; set; }
//Common extension point for all controllers. Inherits from ServiceStack to take advantage of SS powerpack + auth.
public override string LoginRedirectUrl {
get {
return "/Auth/Login?redirect={0}";
}
}
}
I've updated the ServiceStack.Mvc NuGet package that resolved a null reference exception in (v3.9.18+). Try updating and see if that resolves it.

Wcf Data Service Service operations

Getting error when I run the wcf data service with the code following the error message:
"The server encountered an error processing the request. See server logs for more details."
Code:
public class WcfDataService1 : DataService<Entities1>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("GetData", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
[WebGet()]
public IQueryable GetData(int Id)
{
if (assayId > 0)
{
var query = from a in this.CurrentDataSource.Entity
where a.ID == Id
select a;
return query;
}
else
throw new DataServiceException(400, "ID is not valid");
}
}
The same code works when I dont return anything from the operation.
UPDATE: The server logs say:
"WebHost failed to process a request.
Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/44530215
Exception: System.ServiceModel.ServiceActivationException: The service '/MyWcfDataService.svc' cannot be activated due to an exception during compilation. The exception message is: The type 'MyWcfDataService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.. ---> System.InvalidOperationException: The type 'MyWcfDataService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.
at System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
--- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
Process Name: WebDev.WebServer40
Process ID: 1124
For more information, see Help and Support Center at
Can anyone please help me with the solution.
Also, if I want to expose my own entity and not the one created by EF, how to go about doing that.. any ideas??
Just modified the return type to
IQueryable<Entity> and it worked.