Can not run MVC Core project When I Publish - asp.net-mvc

I have created an MVC Core Project(VS 2017) with SQL Server Data Base. My project works correctly in Local IIS with my real Host SQL Server. But when I publish my project to real host, the project does not work. Also I tested a simple project(with out database) in real host that it works correctly. I think I have a problem in connection string. what should I do to solve this problem? I will be tankful for your helps.
here are my some codes:
DataContext.cs
public class DataContext : IdentityDbContext<ApplicationUser>
{
private static bool _Created = false;
public DataContext()
{
if (!_Created)
{
_Created = true;
Database.EnsureCreated();
}
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server = sheva.sepantahost.com;Persist Security Info = False; User ID = hbyby11847; Password = N*w23K+nd5; Initial Catalog = hbyby11847_sheva; ");
}
Web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\News_SourceIran.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</configuration>
my project solution

The application will connect to the database using the identity of the application pool that your IIS website is using. In IIS manager, look at what account that is being used and give that account appropriate permissions in the database.
The exception should also include the account it’s using when trying to connect.

Related

Asp.net Core 2 publish project on IIS returns just a blank page?

I am working on a Asp.net core 2.0 project and i publish it and want to run on IIS.
When the project runs for first time on IIS the database created automatically and seed some tables on IIS and everything is ok. But nothing will by displayed and just returns a blank page without any error.
web.config :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\LibraryProject.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
</configuration>
<!--ProjectGuid: b874d2d9-471b-494a-828c-257173c5a413-->
and Program.cs :
public class Program
{
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
var context = services.GetRequiredService<ApplicationDbContext>();
SeedData.Seeding(userManager, roleManager, context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
}
}
host.Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
}
Also i created logs\stdout folder in publish folder near other dll`s.
I set up IIS from this link. what is wrong in my project?
If you've created your project from the current set of templates, Application Insights is enabled. This fixed it for me:
In your Program.cs add the following method to the WebHost.CreatDefaultBuilder:
.UseApplicationInsights()
Found here: https://developercommunity.visualstudio.com/content/problem/92979/some-aspnet-core-projects-fail-to-add-the-applicat.html
I am a little late to the game here but I don't see anyone else answering. Hopefully this will help someone.
When you see just a blank page and have no response other that the blank page, it can be caused by one of two things. I am sure there are others but these are the two that I have seen:
A corrupt web.config
A web.config that is clashing with IIS. This could happen when a particular section is locked in your IIS configuration.

Why might I not be getting any results from MiniProfiler?

I can't seem to get any results from MiniProfiler.
I can see the XHR POST to /mini-profiler-resources/results returning a 404. The chrome request inspector gives me a standard server 404 page.
A GET on the same URL also returns a 404, but there is a message saying that "no results were found for the specified id" (I did add the id in the querystring).
When I look at /mini-profiler-resources/results-index it just gives me an empty table with the field headings in - name, started, sql, duration, etc.
I've tried a few things - details below - at this stage I am at a loss as to what I can try next. Any pointers or suggestions for debugging this problem would be much appreciated.
Installed Packages:
MiniProfiler (v3.2.0.157)
MiniProfiler.EF6 (v3.0.11)
MiniProfiler.MVC4 (v3.0.11)
Where MVC4 also caters for MVC5. Which this project is.
Relevant Code:
protected void Application_Start()
{
MiniProfilerEF6.Initialize();
MiniProfiler.Settings.Results_List_Authorize = IsUserAllowedToSeeMiniProfilerUI;
MiniProfiler.Settings.MaxJsonResponseSize = int.MaxValue;
Database.SetInitializer<ApplicationDbContext>(null);
GlobalFilters.Filters.Add(new ProfilingActionFilter());
var copy = ViewEngines.Engines.ToList();
ViewEngines.Engines.Clear();
foreach (var item in copy)
{
ViewEngines.Engines.Add(new ProfilingViewEngine(item));
}
}
protected void Application_BeginRequest(Object source, EventArgs e)
{
if (Request.IsLocal)
{
// this IS being hit
MiniProfiler.Start();
}
}
protected void Applicaton_EndRequest()
{
MiniProfiler.Stop(discardResults: false);
}
private bool IsUserAllowedToSeeMiniProfilerUI(HttpRequest httpRequest)
{
return true;
}
In HomeController.cs:
[AllowAnonymous]
public ActionResult Index()
{
var profiler = MiniProfiler.Current;
using (profiler.Step("Doing complex stuff"))
{
using (profiler.Step("Step A"))
{
ViewBag.Title = "Home Page";
}
using (profiler.Step("Step B"))
{
Thread.Sleep(250);
}
}
return View();
}
And in MasterLayout.cshtml:
#using StackExchange.Profiling;
...
#MiniProfiler.RenderIncludes()
I've Tried:
I have set discardResults to false, like this:
protected void Applicaton_EndRequest()
{
MiniProfiler.Stop(discardResults: false);
}
I can confirm that MiniProfiler.Start() IS getting hit when the page loads.
I can also confirm that the mini-profiler-resources/ route IS being found (using Haack's Route Debugger)
I have the following item in the <handlers> section of web.config, and it is in the correct section (e.g. this guy mistakenly put it in the ELMAH config ).
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
I have set all my output caching to 1 second.
I was using a custom applicationhost.config file to test on a custom url.
I tried removing the custom url bindings and just using the standard localhost:51347.
I also tried putting the snippet below into applicationhost.config instead of the standard web.config.
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
In applicationhost.config I tried changing
<section name="handlers" overrideModeDefault="Deny" />
to
<section name="handlers" overrideModeDefault="Allow" />
I've added the following into application_start:
MiniProfiler.Settings.MaxJsonResponseSize = int.MaxValue;
As recommended in this answer, I have tried uninstalling all related packages and reinstalling them in this order:
MiniProfiler
MiniProfiler.MVC4
MiniProfiler.EF6
Update
9 days on, the bounty expired and still no joy :(
If anybody reading this in the future has ideas / suggestions, I'd really like to hear them. MiniProfiler is such a great tool and I'm disappointed that I haven't been able to get it working on this occasion.
If I do find the answer myself, I'll post it.
After running into the same issue I found the answer here which worked fine.
http://www.mukeshkumar.net/articles/mvc/performance-test-with-miniprofiler-in-asp-net-mvc
If you get an error after running application with MiniProfiler.Mvc4 or MiniProfiler.Mvc3 which state “/mini-profiler-resources/includes.js 404 not found” then simply add the following line of code in Web.Config inside web server section.
<system.webServer>
<handlers>
<add name="MiniProfiler" path="mini-profiler-resources/*"
verb="*" type="System.Web.Routing.UrlRoutingModule"
resourceType="Unspecified" preCondition="integratedMode" />
</handlers>
</system.webServer>

How to override Elmah applicationname set in Web.config

We have a multi-tenanted MVC app, meaning that exactly the same app is published to multiple IIS virtual directories / applications, and then the app its self works out who it is, and skins its self (css) accordingly.
This is all very well, but anything logged by ELMAH in our elmah database gets logged under the same applicationName, as this is pulled out of Web.Config elmah section below where everything would be logged as "MyappName" :
<configuration>
[...]
<elmah>
<security allowRemoteAccess="false" />
<errorLog
type="Elmah.SqlErrorLog, Elmah"
connectionStringName="elmah"
applicationName="MyappName" />
</elmah>
</configuration>
The question is therefore how to override the applicationName setting from web.config with something specific so we can distinguish errors for a given tenant web site.
As this is configurable within the web.config, ELMAH are already providing you with a way to specify the application name when the application is deployed to different locations - it's just a case of making use of it.
This would generally be something that you would manipulate as part of your deployment steps. If you are doing it manually then it's going to be a pain, but it could be easily manipulated by using a web.config transform.
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<elmah>
<errorLog applicationName="MyappName" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</elmah>
</configuration>
I wonder if the following might work, if you put the following into your Global.asax:
var service = ServiceCenter.Current;
ServiceCenter.Current = context =>
{
var connectionString = "YOUR CONNECTION STRING";
var container = new ServiceContainer(service(context));
var log = new SqlErrorLog(connectionString) { ApplicationName = "APP NAME HERE" };
container.AddService(typeof(ErrorLog), log);
return container;
};

Miniprofiler and umbraco

I'm running an instance of umbraco 7. But I can't seem to set miniprofiler to work with it.
Set this on my global.asax:
protected void Application_BeginRequest()
{
if (Request.IsLocal)
{
MiniProfiler.Start();
}
}
protected void Application_EndRequest()
{
MiniProfiler.Stop();
}
Also defined the handler on the web.config:
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
Any help is truly appreciated.
MiniProfiler is built in to Umbraco v6 and v7. You don't have to manually setup it. All you have to do is to enable debug mode by setting key in AppSettings:
<add key="umbracoDebugMode" value="true" />
And load page with ?umbDebug=true query string parameter.
Does your global.asax file inherit from the umbraco global http class, or the one where you are writing this code? If the former, it won't work. Try using Web Activator instead. Or inherit from the umbraco global file in your global.asax.cs.

How to get Servicestack Authentication to work in an Umbraco installtion

I can't get SS authentication to work together with an Umbraco installation. Whenever I access a DTO or service with the Authenticate attribute, I get redirected to an umbraco login.
To reproduce:
I've created a new project, and installed Umbraco from Nuget (tried 4.7.1, 4.8.1 and 4.9.0 with same result), and SS from Nuget. I setup SS to run under the /api path in the web.config:
<location path="api">
<system.web>
<httpHandlers>
<add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
</system.web>
<!-- Required for IIS 7.0 -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>
</location>
and added /api to reserved paths to avoid Umbraco handling this:
<add key="umbracoReservedPaths" value="~/umbraco,~/install/,~/api" />
And in the AppHost.cs I've changed the EndpointHostConfig and enabled authentication:
SetConfig(new EndpointHostConfig
{
DebugMode = true, //Show StackTraces when developing
ServiceStackHandlerFactoryPath = "api"
});
//Enable Authentication
ConfigureAuth(container);
And I've changed the connectionstring in ConfigureAuth to use the Umbraco database:
var connectionString = ConfigurationManager.AppSettings["umbracoDbDSN"];
Finally I set the attribute on HelloWorldService:
[Authenticate]
public class HelloService : ServiceBase<Hello>
{
protected override object Run(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
I then access the HelloWorldService through REST Uri:
http://localhost:56835/api/hello
and right away I'm redirected to:
http://localhost:56835/apilogin?redirect=http%3a%2f%2flocalhost%3a56835%2fapi%2fhello
and presented with the default Umbraco 404 page, which means that SS suddenly makes Umbraco handle the authentication. If I remove the Authenticate attribute, SS handles the request perfectly.
What am I missing?
It seems that FormsAuthentication is just plain annoying, and when it spots a 401 it changes that to 302 login.aspx.
My solution was use use the idea from this link: http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx
In short it revert the 401->302 change from FormsAuthentication back to 401.
I changed it a bit in the detection code:
if (response.StatusCode == 401 && request.RawUrl.ToLower().StartsWith("/api"))
and removed the Register and added it manually AFTER the FormsAuthentication module in web.config

Resources