This is my first time deploying an MVC2 app (.NET4) on IIS7.5. I'm using StructureMap and Fluent NHibernate, and everything runs fine locally using integrated security. The application does render the first page (controllername/pagename), but throws an error on the next one which is (controllername/pagename/id).
I have ran %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir.
HttpRedirection and HttpExceptions are enabled.
This is the 404 error from View Source:
[HttpException]: The controller for path '/conrollername/pagename/1' was not found or does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at CustomerResponses.Infrastructure.StructureMapControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in C:\Apps\Development Source\CustomerResponsesApplication\trunk\CustomerResponses\Infrastructure\StructureMapControllerFactory.cs:line 19
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Another link gives me 500.24 error:
HTTP Error 500.24 - Internal Server Error
An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.
Does anyone have any ideas?
Thanks
Part on Web.Config
system.webServer - section
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<handlers>
<add name="UrlRoutingHandler"
preCondition="integratedMode"
verb="*" path="UrlRouting.axd"
type="System.Web.HttpForbiddenHandler,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
<!--<handlers>
<remove name="MvcHttpHandler" />
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler" />
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>-->
Global.asax
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.gif/{*pathInfo}");
routes.IgnoreRoute("{*datepick}",
new { datepick = #"(.*/)?jquery.datepick.css(/.*)?" });
// ignore datepick.css file
routes.IgnoreRoute("{*favicon}",
new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.IgnoreRoute("{*chevron}",
new { chevron = #"(.*/)?Images/Chevron.gif(/.*)?" });
routes.IgnoreRoute("{*iconhome}",
new { iconhome = #"(.*/)?Images/IconHome.gif(/.*)?" });
routes.MapRoute("test", "testroute",
new { controller = "compresponses", action = "list" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "compresponses",
action = "list",
id = UrlParameter.Optional
} // Parameter defaults
);
One of the problems is:
your web.config file contains too much information.
IIS 7.5 when runs in intergated mode does not require any additional settings.
I would recomend to create blank mvc application and publish it onto webserver.
also i have seen
the error :
[HttpException]: The controller for path '/conrollername/pagename/1' was not found or does not implement IController. at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) at
where it says that the dll either system.web or system.web.mvc is not referenced from project.
My solution( might be not the best) but is: Right button on project where the error occured and copy the dlls local and this should help with the error.
as for error:
Another link gives me 500.24 error: HTTP Error 500.24 - Internal Server Error An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.
the best is to have iis console installed and open the project using iis console.
Change your application pool properties to:
.NET Framework Version
-- .NET Framework *version*
Pipeline Mode
-- Classic
Related
I have an ASP.NET Core application running as a Windows Service. Due to project requirements, I am using Entity Framework v6.3 (as opposed to using EF Core).
I am having trouble retrieving the correct connection string when performing a migration and also upon publishing the service to a server. When running the service locally, the connection string is retrieved successfully.
As I understand it, Entity Framework 6 is supposed to retrieve connection strings from web.config or app.config files, right? Therefore, I have an app.config file containing two connection strings, e.g.
<connectionStrings>
<add name="DataContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
<add name="CrmContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
</connectionStrings>
In my Startup class, I have registered both database contexts, e.g.
services.AddTransient<DataContext>();
services.AddTransient<CrmContext>();
On a Razor page, when I instantiate both data contexts on my local machine I can see the correct connection string is being resolved for both contexts (by using _crmContext.Database.Connection.ConnectionString).
When I attempt to add a migration using the update-database command on my CrmContext (automatic migrations enabled), the correct connection string isn't resolved. Instead, it defaults to creating a LocalDB database using the default connection string: (localdb)\MSSQLLocalDB
How come it isn't using the connection string I have provided in my app.config file? I also a web.config file but it doesn't resolve from there either.
CrmContext.cs
public class CrmContext : DbContext
{
public CrmContext() : base("CrmContext")
{
Database.SetInitializer<CrmContext>(null);
}
public IDbSet<CustomerDetails> CustomerDetails { get; set; }
}
CrmConfiguration.cs
internal sealed class CrmConfiguration : DbMigrationsConfiguration<CrmContext>
{
public CrmConfiguration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(CrmContext context)
{
...
context.SaveChanges();
}
}
I've tried to explicitly update the CRM connection by specifying my CrmConfiguration file:
update-database -ConfigurationTypeName CrmContext
When I do this, it creates and updates the LocalDB database instead of using my connection string.
I've also tried to explicitly referencing the connection string:
update-database -ConnectionStringName "CrmContext"
This results in this error:
No connection string named 'CrmContext' could be found in the
application config file.
My CrmContext class exists within my ASP.NET Core windows application where my DataContext class exists in a separate 'Data' project (as it's shared with an ASP.NET MVC v5 application)
When I publish my service and install the application as a Windows Service, I found that it also doesn't pick up the connection strings at all from any of the config files - it again just looks for the default localdb database. As I understand, it should pick it up from my PaymentBatchProcessorService.exe.config file, right?
My PaymentBatchProcessorService.exe.config file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DataContext" providerName="System.Data.SqlClient" connectionString="redacted" />
<add name="CrmContext" providerName="System.Data.SqlClient" connectionString="redacted" />
</connectionStrings>
</configuration>
As per Microsoft documentation, it should be possible to load in the additional XML configuration files via the following code in the Program.cs file, but EntityFramework still didn't pick up the connection strings:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostingContext, config) =>
{
var workingDirectoryPath = Environment.GetEnvironmentVariable(EnvironmentVariables.ServiceWorkingDirectory);
config.AddXmlFile(Path.Combine(workingDirectoryPath, "app.config"));
config.AddXmlFile(Path.Combine(workingDirectoryPath, "web.config"));
})
e.g. in the above sample, the working directory path resolves to the location where my .exe is for the Windows Service.
Thanks for reading this far!
When you deploy your service, the .config file should instead be called servicename.exe.config. It should reside on the same folder where the service was registered with installutil. See Windows service app.config location.
I'm adding an SQL database to my Azure API App. I have an empty SQL database which I created separately via portal.azure.com. My problem is I don't know how to set up the connection string so that my app uses the Azure database.
I have followed the Code First Migrations article, but I'm stuck on the deployment phase. I cannot see any connection configuration in any of the files in the project.
How do I set the connectionString to be used by the app when it's deployed in Azure?
More info:
To be precise, I can see 2 things:
Commented out connectionStrings sections in Web.Debug/Release.config files.
Some EF configuration in Web.Config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
(...)
When I execute tests locally I can see Database.Connection.ConnectionString is
Data Source=(localdb)\mssqllocaldb;Initial Catalog=XDataAPI.Models.MyContext;Integrated Security=True;MultipleActiveResultSets=True
BTW. The publish window states that no database have been found in the project. (This doesn't really bother me, it's a secondary issue)
Edit:
DbContext, as requested:
public class MyAppContext : DbContext
{
public DbSet<Organisation> Organisations { get; set; }
}
Pass in the connection name as param to your constructor, and then use the same connection name when setting up your connection string in your web.config, like this:
public class MyAppContext : DbContext
{
public MyAppContext():base("MyConnectionName"){}
public DbSet<Organisation> Organisations { get; set; }
}
And then, in web.config:
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="MyConnectionName" connectionString="Server=tcp:test.database.windows.net,1433;Database=testdb;User ID=test#test;Password=p4ssw0rd!;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
<configuration>
If you want to run from a local machine, remember that you need to allow incoming connections from your IP on your Azure database server firewall.
If you set up the SQL Server VM, then
<add name="DataContext" connectionString="Data Source=VMname.cloudapp.net; Initial Catalog=catalog; User ID=login;Password=password; MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
If you set up the SQL Azure, then that tutorial should be used.
As for the connection string place, please refer to some documentation. You use LocalDB, instead of that you should use the SQL Server.
You should be able to just update the connection string for your data context in the web.config to use you Azure SQL Database. For my testproject it is just at the top of web.config:
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="WebApplication4Context" connectionString="Server=tcp:test.database.windows.net,1433;Database=testdb;User ID=test#test;Password=p4ssw0rd!;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
<configuration>
Don't forget to also update the firewall settings of your Azure SQL Database Server to make it accessible for your application.
Edit: You can also change the database connection for just your Azure environment by adding the your Azure SQL DB in the Publish dialogue:
If the connection string is missing web.config, then it is using the default name which is DefaultConnection and it refers to the localdb instance that gets installed with SQL or SQL Express.
To configure it, you have to first create a SQL DB on Azure, from the Portal, create a new database and give it a name and make sure it exist in the same resource group and region to decrease the latency and improve the performance.
Open the created database and you will find the connection string for many platforms, copy the one for .Net and go to the Web App settings, you should find a place for connection strings, add a new one and name it DefaultConnection and add the value a the connection string you just copied from the database blade
When you run the application for the first time, code first will connect to the database and apply the migration if you specified that during the publish wizard which adds some configuration in web.config as well.
For .Net FW 4.5 or above:
1. Your DbContext class:
public class MyAppContext: DbContext
{
public MyAppContext() : base("YourConnectionStringKey") { }
public DbSet<Organization> Organizations{ get; set; }
}
2. Your Web.config:
<connectionStrings>
<add name="YourConnectionStringKey" connectionString="DummyValue" providerName="System.Data.SqlClient" />
</connectionStrings>
3. In your Azure WebApp settings, add the connection string (which will be automatically injected into your Web.config at runtime)
If you're not developing using the .Net framework, see https://azure.microsoft.com/en-us/blog/windows-azure-web-sites-how-application-strings-and-connection-strings-work/ for further details.
Searched google and using Enterprise library data access to connect database.
Installed only data access pack using https://www.nuget.org/packages/EnterpriseLibrary.Data/.
After added to the project, I've set the configuration as follows,
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
</configSections>
<dataConfiguration defaultDatabase="dProvider" />
<connectionStrings>
<add name="dProvider" connectionString="server=local;Initial Catalog=n;uid=sa;pwd=pwd"
providerName="System.Data.SqlClient" />
</connectionStrings>
Called through the application like the following,
Database db;
string sqlCommand;
DbCommand dbCommand;
db = DatabaseFactory.CreateDatabase("dProvider"); or DatabaseFactory.CreateDatabase();
After run the application, I got the following exception,
{"Database provider factory not set for the static DatabaseFactory. Set a provider factory invoking the DatabaseFactory.SetProviderFactory method or by specifying custom mappings by calling the DatabaseFactory.SetDatabases method."}
What mistake I made ? How to solve this issue ?
Finally found the answer. It has been occurred because of the configuration section.
I've used version 6, but here I've mentioned like version 5 in the configuration section. So the error has occurred.
I've replaced the configuration section like following, It worked perfectly in good way. :-). Thanks a lot for the helpers.
<configSections>
<section name="dataConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
Microsoft.Practices.EnterpriseLibrary.Data"/>
</configSections>
and used DataBaseProviderFactory class to create instance.
DatabaseProviderFactory factory = new DatabaseProviderFactory();
db = factory.Create("dProvider");
Problem:
I need to create a web project with a controller that times out.
What I have done:
Create a new web application
Empty the web.config, and write the values below:
.
<?xml version="1.0"?>
<configuration>
<system.web>
<httpRuntime executionTimeout="1" />
<compilation debug="false" />
<httpModules>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
</configuration>
Write the following code to the controller:
.
public class DefaultController : Controller
{
public EmptyResult Index()
{
System.Threading.Thread.Sleep(3000);
Response.Write("ScriptTimeout: " + HttpContext.Server.ScriptTimeout);
return new EmptyResult();
}
}
When run, the server sleeps for 3 seconds, then returns the response without any timeout error. ScriptTimeout value is 1.
Question:
Any idea what went wrong?
Do you want a 408 Request Timeout HTTP status code?
public ActionResult Index()
{
return new HttpStatusCodeResult(408);
}
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
The executionTimeout attribute on the <httpRuntime/> element is only taken into account if debug="false" on the <compilation/> element.
Try removing the debug attribute or explicitly setting it to false. Of course, you'll have to run your application without debugging to test it.
See http://msdn.microsoft.com/en-gb/library/vstudio/e1f13641(v=vs.100).aspx for more details.
I created a new mvc 2 project to learn mvc. I'm trying to do something like the following:
Webconfig
<appSettings>
<!-- WEB SITES -->
<add key="LiveWebAddress" value="www.mydomain.org"/>
<add key="DevWebAddress" value="localhost/mydomain"/>
<add key="TestWebAddress" value="test-2/mydomain"/>
</appSettings>
in the controller I am trying to do this:
public ActionResult link()
{
//return View();
return RedirectToAction(
System.Configuration.ConfigurationManager
.AppSettings["LiveWebAddress"]
.ToString()
);
}
Am I headed in the right direction? I'm getting a null reference exception.
You should probably use WebConfigurationManager instead. In addition, I'm not sure doing this in the controller is the best option.