ASP.NET Core console app cannot find controllers - c#

I have created a simple .NET Core console project that includes ASP.NET core, as below:
MyProject.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.1" />
</ItemGroup>
</Project>
And in my Program.cs:
public class Program
{
static void Main()
{
WebHost.CreateDefaultBuilder()
.UseKestrel()
.UseStartup<Startup>()
.UseUrls("http://localhost:1234")
.Build()
.Run();
}
}
In my Startup.cs I have:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
And a single controller in a Controllers folder:
public class HomeController : Controller
{
[Route("Home/Index")]
public IActionResult Index()
{
return Ok("Hello from index");
}
}
But nothing I can do seems to make it hit my controller.
The logs are showing that requests to http://localhost:1234/Home/Index are coming through Kestrel, but 404ing.
What am I missing? I have also tried specifying routes, but have had no luck in making it find the controller.

I’m not sure if this is the reason why but your kestrel is using the old 1.1 version, in order for certain process to run properly such as migrations, which relies on duck typing you should declare a BuildWebHost method:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
There’s more information in the docs. If this doesn’t work I would create a new project and move things across manually. The only other issue I could think of would be your package manager cache is messed up or you have too many run times installed on your machine

Remove:
.UseUrls("http://localhost:1234")
That could be as a result of separate URLs in the launchSettings.json
Afterwards add the routing and endpoints to the middleware,
app.UseRouting();
app.UseEndpoints(e =>
e.MapControllerRoute( name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
);
Also, register the mvc service
services.AddMvc();

Related

Can't find views after upgrading to .net 6 and deployed on server

I am having a weird issue after I upgraded a very simple .net core 3.1 MVC app to .net 6. I used the upgrade assistant and also followed the Microsoft's guideline very carefully. The absurdity of the problem is that on my local machine everything works fine, but on the server I keep getting the following error. Also, prior to the upgrade, it worked fine both locally and on the server:
I did mention it totally works on my computer, but also just as a proof that the file it says it cannot find does exist:
Here is the code for the Startup.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(15);
options.Cookie.HttpOnly = true;
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc(x => x.EnableEndpointRouting = false).AddRazorRuntimeCompilation();//.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllersWithViews();
services.AddKendo();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseRouting();
app.UseStaticFiles();
app.UseSession();
app.UseMvc().UseEndpoints(x => x.MapControllers());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
}
}
and just in case the code for Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, logging) =>
{ logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
if (hostingContext.HostingEnvironment?.EnvironmentName?.Equals("Debug") == true)
{
logging.AddConsole();
logging.AddDebug();
}
logging.AddEventLog(new EventLogSettings
{
SourceName = "wcb.ACIi.web"
});
})
.Build();
}
If including views in the main assembly is not essential you can:
add this to your property group: <UseRazorSourceGenerator>false</UseRazorSourceGenerator>
This will prevent including the views in the main dll and create the other. This helped us as we found that on the build server dotnet publish was not creating the the AspNetCoreGeneratedDocument namespace (we used dotPeek to determine this). All of the microsoft targets were installed and it still would not build correctly.

ASP.NET Core MVC App on Linux - Raspberry Pi Not displaying correctly

I got an ASP .Net MVC WebApp running on raspberry Pi, with NGINX Server.
It's a blank project, the default MVC project.
I got it deployed and accessible via the network. However, it does not display correctly either on the Pi or accessing via from my Laptop.
It does display correctly when I run it from the Debug in my VS.
Running on Debug from VS:
Same app running "Dotnet App.dll" from Linux:
I was wondering if I am missing something on the Program.cs or Startup.cs, or if I am publishing it wrong.
Publish Options: File / Release / netcore3.1 / Framework-Dependent / Portable (Tried Linux-arm - same)
Program.cs:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls("http://localhost:5000");
webBuilder.UseStartup<Startup>();
});
}
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.Configure<ForwardedHeadersOptions>(options =>
{
options.KnownProxies.Add(IPAddress.Parse("192.168.1.1"));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
App Install Folder in the Linux:
As per the comments, NGINX Files were pointing to the wrong directory. The problem was the configuration of "sites-enabled" location, not pointing to where the HTML lives.
More info see the NGINX Docs or the LINK:
Tutorial ASP.NET CORE - PI
Solved!

.NET Core 3.1 Console App as a Windows Service

I currently have a pretty big console app running with ASP.NET Core 3.1. I have been tasked with now making this work on one of our servers as a Window Service. I have everything ready to make it run as a service on the server itself, however, the one thing I am stuck on at the moment is how to actually change it in code to make it run as a service without breaking it.
I have found a couple of tutorials like this that do explain how to run a console app as a service, however, all of them that I have found start from a fresh project. My issue is that my current project has already been written. The main problem that I am asking for help with is how would I go about making my project work as a windows service while also keeping the functionality that is currently in a startup.cs. For context, here is my current startup.cs and program.cs:
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSignalR();
services.AddTransient<SharePointUploader>();
services.AddTransient<FileUploadService>();
services.AddSingleton<UploaderHub>();
//services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
services.AddAuthorization();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHttpsRedirection();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<UploaderHub>("/uploadHub");
});
}
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
//NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog();
}
I don't really understand how this is supposed to work when run as a windows service (based on tutorials like linked above). Any help would be greatly appreciated.
I forgot about answering this question as I solved it a few hours later after I asked it, but you can just add ".UseWindowsService()" to the Host.CreateDefaultBuilder(args) line.
eg:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService() //<==== THIS LINE
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog();
Use IWebHostBuilder instead of IHostBuilder:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
// Configure the app here.
})
.UseNLog()
.UseUrls("http://localhost:5001/;" +
"https://localhost:5002/;")
.UseStartup<Startup>();
You also need the following packages:
Microsoft.AspNetCore.Hosting;
Microsoft.AspNetCore.Hosting.WindowsServices;
Modify your main function:
bool isService = !(Debugger.IsAttached || args.Contains("--console"));
var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray());
var host = builder.Build();
if (isService)
{
host.RunAsService();
}
else
{
host.Run();
}
For installation of the service use the tool sc.exe. You can run the app as console app by passing --console as argument to the app. For debugging you need to pass --console as well.
In my case, I did have a "UseWindowsService()" statement included in my host builder setup. However, I have that configuration broken out across multiple lines and the problem was that, at some point during development, I had ALSO placed a:
UseConsoleLifetime()
statement into the mix further down in the code. Once I figured out what was going on, using the following partial code block resolved the issue:
var hostBuilder = Host.CreateDefaultBuilder(args);
if (WindowsServiceHelpers.IsWindowsService())
{
hostBuilder.UseWindowsService();
}
else
{
hostBuilder.UseConsoleLifetime();
}
Note, WindowsServiceHelpers is a static class in the "Microsoft.Extensions.Hosting.WindowsServices" namespace.

Routing is not working with self-hosted web API [duplicate]

This question already has an answer here:
WebApi giving 404 whilst debugging; works when published
(1 answer)
Closed 3 years ago.
This is essentially what I have, a very simple set of three files with fresh asp.net core 2.1 (actually copy-pasted from tutorials):
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Then goes the simplest startup
class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
And default values controller
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}
No matter what I call I see in console same 404 error:
Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/values
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 105.0181ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/api/values
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 2.6016ms 404
etc
I tried adding default route both with app.UseMvcWithDefaultRoute(); and specifying it manually. I tried removing route attributes when used the default route. Also tried adding AddControllersAsServices(). But result is still same - 404. When I setup custom handler in app.Run then it works without any issues.
csproj (I have replaced default Microsoft.AspNetCore.All dependency, but routing still does not work)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.0" />
</ItemGroup>
</Project>
This was rather difficult to track down, but the problem boils down to this in your .csproj:
<Project Sdk="Microsoft.NET.Sdk">
As you are building a web application, you need to instead reference the Web Sdk, as follows:
<Project Sdk="Microsoft.NET.Sdk.Web">
I managed to reproduce and fix your issue with this small change.
For me it helped adding AddApplicationPart after AddMvc like this:
.AddMvc()
.AddApplicationPart(typeof(Startup).Assembly)
you can try change code to this:
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
[Route("api/values")]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}
The atribute Route can use for asigning an specific route to a function on api or view.
then to call you can use:
'localhost:5000/api/values'

ASP.NET Core 2.0 IIS Web Hosting

I created an ASP.NET Core 2.0 MVC Web Application and I need help getting it setup to run with IIS on Windows Server 2016.
So far, I have followed and completed all the steps on https://learn.microsoft.com/en-us/aspnet/core/publishing/iis?tabs=aspnetcore2x up to the section Application configuration. This is the step that I'm stuck at and have not been able to complete the steps below it.
I'm going to post my Startup.cs and Program.cs code as to what I have now. I'm not sure if those two files need modified.
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<WinTenDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
The issue that I was having I finally figured it out. It had to do with the account that was setup for me on the Domain that was added to the Security on the SQL Server. Once I provided the correct permissions to that AD account I no longer received the error messages.

Categories

Resources