InitializeSimpleMembershipAttribute returns TargetInvocationException - c#

I am still a relatively inexperience with Visual Studios and C# so please let me know if necessary information has not been provided or I am unclear in my description.
I have an MVC 4 project in Visual Studio 2010 Web Developer Express and I am attempting to set up basic Forms Authentication. I have used the ASP.NET Configuration Manager to set up a couple test users and roles. The Configuration Manager has also created the ASPNETDB.MDF database in my App_data folder which has been included in the project.
I am currently using the generated AccountController and Account views.
Whenever I attempt to access a HTTPGET or HTTPPOST method with which has the [Authorize] attribute, a TargetInvocationException is thrown from the following method in the InitializeSimpleMembershipAttribute class:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
When viewing the details of the exception, the inner exception states that "The ASP.NET Simple Membership Database could not be initialized."
The inner exception of the above inner exception states that it "Could not find the conceptual model type for" a given model.
The model that was not found belongs to an ADO.Net [.edmx] file which is generated from a database. The model that it cannot find is alphabetically the first table/class in the database, so it likely also applies for every class from that database.
I am not sure if it is important, but I use a database separate from the ASPNETDB.MDF to store information enter on the website.
I do not understand why the LazyInitializer.EnsureInitialized() method may be causing this problem.

Have you checked the connection string used by WebSecurity.InitializeDatabaseConnection in Global.asax.cs Application_Start() - this could potentially cause the issue.
If the named connections string is correct are you sure the dbContext connection string is correct:
public SomeContext(): base("MyConnectionStringName")
{
}

Related

.NET Core: security access based on group membership

I'll make this post short and get straight to the seriousness of the situation. Our application has the concept of "Organizations" which are comprised of "Members". We recently found a huge security flaw in our application. If a Member that does not belong to a specific Organization (but is logged into the application) gets access to a URL for any of that Organization's pages, he/she can access that page.
Is there something built into .NET Core 3.0 or Web API that would allow us to stop users from being able to access Organization pages that user is not a Member of? The only way I can think to do it is check if the Member (based on their MemberId) belongs to the Organization (based on OrganizationId). However, that check would have to be added to every single API controller. There has to be a better way! Any help is appreciated...
Decided that I am going to:
1) Create a custom exception
2) Throw it in a base repo class that all of my derived classes are inheriting from
3) Propagate it up and catch it at the base controller class using an ActionFilter
4) Return 403 (w/ custom exception error message) to user (Angular)
5) Have the Angular HTTP interceptor handle the error message, meaning show to user
If anyone has a better idea please let me know.

Error: your connection to this site is not private Asp.Net. MVC5

I'm setting up a new server with windows Azure VM for a asp.net mvc 5 application. I'm able to open every page of the application without a problem with an exception of one controller. i.e. whenever I try to open a page belong to a specific controller, it prompts me for user name & password as below.
I use the same application in a different Windows Server 2016 VM without any issues.
I don't see any errors of the application/IIS logs either. I don't have any https requirements in the application.
What may be causing this behaviour?
namespace App.Controllers
{
public class ReportsController : BaseController
{
private readonly IReportRepository reportRepository;
public ReportsController(): this(new ReportRepository()){
}
public ReportsController(IReportRepository reportRepository){
this.reportRepository = reportRepository;
}
public ViewResult Action()
{
return View(reportRepository.All);
}
}
}
namespace App.Controllers
{
[Authorize]
public class BaseController : Controller
{
}
}
UPDATE: I renamed the ReportsController to AppReportsController and the issue disappeared.
i.e. I get the above prompt when I try to access
http://domain/Reports/Action
but not for
http://domain/AppReports/Action
Could you please someone explain to me what's going on here? Does it mean that "Reports" is reserved by the framework or something?
This is an authentication issue. In my case, it solved by below steps:
1- Go to IIS manager, in the left pane, expand the server root and select your web application from Sites node.
2- In the Home screen, go to IIS section and select Authentication.
3- Enable Anonymous Authentication.
4- Then, select Edit and set Edit Anonymous Authentication Credentials to Application pool identity.
I know this was an old post however I stumble on this one because I encountered the same error as the OP does.
I have solved this one in case there's someone encounters the same as this.
but the solution may vary depends if we have the same applications installed.
check if the web server / server has an installation of sql server.
check if there is reporting services installed.
remove / uninstall the reporting services from the application control panel
follow this link if you don't know how to remove the report service How to remove Report Service
Please check again if you still encounter the same error. Cheers!
The browser will tell you your connection to the site is not private if you don't use transport layer security (i.e. HTTPS) in your web application, and you are being asked to enter data - in this case your credentials. Doing this is dangerous because that data can easily be sniffed by a malicious person.
There is no reason in today's world to not have a secure site, I strongly recommend you get a certificate (they are free and super easy!)
Just don't use "Reports" use "Report" instead. Controller name ReportController not ReportsController. It'll be alright. I've faced the problem and this is the solution I've got.

How do I resolve my Invalid object name 'dbo.AspNetUsers' error?

I changed my connection string when starting a new mvc project because I needed to use some info out of an existing database. Now I get a "Invalid object name 'dbo.AspNetUsers' when I try to load the startup page. A quick google search says the issue happens because you are connecting to an existing database using asp.net users. Still, this should not occur since I am not using code first migrations, right? What is more, I am using Active Directory to authenticate my users instead of individual user accounts.
In addition, the AspNetUserstable does not exist in the database I am calling in the web.config:
Due to the fact that I am not using the UserStore or the ApplicationUser provided by the Individual User Accounts defaults I needed to change this:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
to
public class ApplicationDbContext : DbContext
Optionally If you are using Code First Migrations you could add the initial migrations, remove all of the sql code from the up and down methods, and finally update the database. Even though the tables will still not exist it seems to satisfy the compiler and your project as the error goes away and the page loads as expected.

ASP.NET MVC: Check database connectivity on application startup

1- Sometimes my SQL Server is down for maintenance, so when I try to run my ASP.NET MVC application i face the yellow error screen with error network-related or instance-specific error occurred while establishing a connection to SQL Server.
Since I don't know the sequence of events in ASP.NET MVC I want to know where I should check connectivity so can I redirect user to a view informing him/her about this situation (instead of displaying this error page).
I saw this answer in asp.net forum but I couldn't understand how can I handle this inside global.asax.
2- Is it possible to do some changes which for every database connection error I can redirect user to that information page? I mean is it possible to define global exception handler for database connection error?
P.S. My connectionString in web.config is named DefaultConnection.
I think you can prepare a global filter(if you have many controllers and don't want to decorate each with an attribute) and just use it to check what kind of exception has been thrown and e.g. redirect user to some custom view:
public class SqlExceptionFilter: IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// Do your logic
}
}
And then just register it in Global.asax in Application_Start() method:
GlobalFilters.Filters.Add(new SqlExceptionFilter());

DNN Database Repository Reuse in Console Application

I have a project based on the Chris Hammond, Christoc, module template. I have a ton of code that I use to access data an external database. In my repositories I change the database from the default to whichever I need for that particular object. I do so with code that looks like this:
using (IDataContext ctx = DataContext.Instance(MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY))
{
var rep = ctx.GetRepository<Product>();
products = rep.Get().ToList();
}
The default database is switched in the call to .Instance(). The repositories are used by my custom DNN modules. The repository is part of the solution that contains multiple custom modules. When I compile and install using the Extensions part of DNN, everything works well. In the code above, MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY is found in a file MyModuleSettingsBase.cs file of my module solution. It is set to a simple string like "ProductDatabase". In the solution for the base DNN install (not the module solution), within the web.config file, there is a value in <connectionStrings> with name="ProductDatabase" which contains the actual connection string. This all links up fine on the DNN website.
Now I am writing a console application that does some monitoring of the site. I want to access the database to check values in the product table. I would like to reuse all of the repository code I have written. In an attempt to do so, I added a reference to the MyModules.dll file so I would only have one copy of the base code. This works to give me access to all the objects and the associated repositories but when I attempt to query data it fails. When debugging I can see that it fails on the line:
using (IDataContext ctx = DataContext.Instance(MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY))
When viewed in a debugger, the string value MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY is correctly set to "ProductDatabase" but the code is unable to link this with the actual connection string. I don't know where it would be checking for the connections string when running from my console application. I attempted to put a <connectionStrings> section into my App.config file but this didn't do the trick.
Is it possible to have MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY map to the connection string in an external application which references the DLL?
If so, where can I set the value of my connection string so it matches up to the key value stored in MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY?
I was faced similar problem 3 months ago, at that time I want to use DNN core libraries in my console application but I was failed.
I placed my queries in DNN official forum website and I got a valid response from Wes Tatters (DNN MVP).
Here is the post link: Reference URL
As your requirement of monitoring, I suggest you to create DNN Schedule Application. You can schedule it within DNN (Host->AdvancedSettings->Schedule), even good point is that you can use your repositories (DNN Libraries) in that schedule application.
I hope it solved your problem. Let me know if you have any questions.

Categories

Resources