Razor View Does Not Display Records - asp.net-core

I am new to ASP.NET Core MVC. I created an ASP.NET Core MVC project in VS 2022. I used EF power tool to create DbContext and model classes, added connection string route map in program.cs.
But my view is blank and does not display any records from controller. Actually, the HomeController never gets hit when debugging. I have no idea where the problem is and what code I am missing.
Program.cs:
using Courses.Models;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();
//add connection string
builder.Services.AddDbContext<DbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/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.UseRouting();
app.UseAuthorization();
//map route
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.MapRazorPages();
app.Run();
HomeController
using Microsoft.AspNetCore.Mvc;
using Courses.Models;
namespace Courses.Controllers
{
public class HomeController : Controller
{
private readonly DbContext _db;
// GET: HomeController
public HomeController(DbContext context)
{
_db = context;
}
public ActionResult Index()
{
var subjectList = _db.subjectTable.OrderBy(a => a.Subject).ToList();
return View(subjectList);
}
...
}
}

Never mind. When I created the project, it generates a Pages folder with pages underneath it. My HomeController gets hit after I removed the Pages folder.

Related

ASP.NET Core 6 OData Swagger UI always shows $count query

I created a new ASP.NET Core Web API project with Swagger and added an ODataController. The Swagger UI shows my Users route as expected, and it works. But the Swagger UI also unexpectedly shows Users/$count:
Why is $count there? Can I prevent it from appearing?
I'm using Microsoft.AspNetCore.OData 8.0.10 (the latest). I get the same results with Swashbuckle.AspNetCore 6.2.3 (the template default) and 6.3.1 (the latest).
My entire controller:
public class UsersController : ODataController
{
private readonly ErpContext _db;
public UsersController(ErpContext db)
{
_db = db;
}
[HttpGet]
public IActionResult Get()
{
return Ok(_db.Users);
}
}
My entire EDM:
public static class EntityDataModel
{
public static IEdmModel Build()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<User>("Users");
return builder.GetEdmModel();
}
}
My entire startup, in case there's some order sensitivity or something:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContextFactory<ErpContext>(options =>
{
options.UseSqlServer(builder.Configuration["ConnectionStrings:DefaultConnection"]);
});
builder.Services
.AddControllers()
.AddOData(options =>
{
options.AddRouteComponents("odata", EntityDataModel.Build());
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Note that my controller action does not have [EnableQuery] and my ODataOptions does not have Count() or any other query. The unwanted $count query doesn't even work unless I add those.
I've reproduced the problem in a minimal project with an in-memory DB.

Asp.Net Core 6 Scoped Filter inject UserManager

I'm working on linking Twilio Verify into an Asp.Net Core web site. I'm pretty sure I have to figure out how to access UserManager in the filter (constructor). But, I don't know how to access it.
My VerifyFilter:
public class VerifyFilter : IAsyncResourceFilter
{
private readonly UserManager<ApplicationUser> _manager;
public VerifyFilter(UserManager<ApplicationUser> manager)
{ _manager = manager; }
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{ // cut just to make listing a bit shorter }
}
My program.cs file currently looks like this:
builder.Services.AddScoped<VerifyFilter>();
What I don't know is how I get the UserManager so I can pass it in.
I have another scoped right above it and I had to do this to get Verification to work.
Configuration.Twilio twilio = new Configuration.Twilio();
builder.Services.AddScoped<IVerification>(t => new Verification(twilio));
So I'm sure it's just a matter of figuring out how to get UserManager to pass in as a constructor, but with MinimalAPI and .Net Core 6.0, I don't know where it is at.
My entire program.cs file:
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using test4.Data;
using test4.Filters;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services
.AddDefaultIdentity<IdentityUser>(
options =>
{
// These will get updated to production versions later.
options.SignIn.RequireConfirmedAccount = true;
options.Password.RequiredLength = 1;
})
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddRazorPages();
builder.Services.AddScoped<VerifyFilter>();
builder.Services.AddControllers(op =>
{
op.Filters.Add<VerifyFilter>();
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/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.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
Any suggestions?
Thanks,
Nick
You could try to register the filter via the following code:
//register the Identity service
//register the custom filters.
builder.Services.AddControllers(op =>
{
op.Filters.Add<VerifyFilter>();
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

.Net Core 3 Identity register or login links not functional [duplicate]

After having a hard time getting my area to show with endpoint routing i managed to fix it in this self answered thread (albeit not in a very satisfactory way) : Issue after migrating from 2.2 to 3.0, default works but can't access area, is there anyway to debug the endpoint resolution?
However Identity UI doesn't show at all for me, i get redirected on challenge to the proper url but the page is blank. I have the identity UI nugget package added and, changing from mvc routing to endpoint routing, i didn't change anything that should break it.
I also don't seem to do much different than what the default project does and identity works there even if i add a route as i did in my hack.
As often the issue hides around the line and not on it i'm posting my whole startup file.
Regular (default) controllers work.
Admin area works (one of the page doesn't have authentication and i can access it)
Any other Admin area page redirect me to /Identity/Account/Login?ReturnUrl=%2Fback (expected behavior) but that page as well as any other /Identity page i tested is blank with no error while running in debug and with a debugger attached.
Any help is most appreciated, full startup bellow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using FranceMontgolfieres.Models;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
namespace FranceMontgolfieres
{
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.AddSingleton<IConfiguration>(Configuration);
services
.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services
.AddDbContext<FMContext>(options => options
.UseLazyLoadingProxies(true)
.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services
.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<FMContext>();
services
.AddMemoryCache();
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = Configuration.GetConnectionString("SessionConnection");
options.SchemaName = "dbo";
options.TableName = "SessionCache";
});
services.AddHttpContextAccessor();
services
.AddSession(options => options.IdleTimeout = TimeSpan.FromMinutes(30));
services.AddControllersWithViews();
services.AddRazorPages();
}
// 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();
app.UseDatabaseErrorPage();
}
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.UseRouting();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapAreaControllerRoute("Back", "Back", "back/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute("default","{controller=Home}/{action=Index}/{id?}");
});
}
private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
string[] roleNames = { "Admin", "Manager", "Member" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
}
}
The Identity UI is implemented using Razor Pages. For endpoint-routing to map these, add a call to MapRazorPages in your UseEndpoints callback:
app.UseEndpoints(endpoints =>
{
// ...
endpoints.MapRazorPages();
});

asp.net core 3 routing

In my Asp.net core 3 project I am using some controler to access from js code to do some stuff and also using Razor pages at the same time.
at the configure service section :
services.AddControllersWithViews();
services.AddRazorPages();
I added both RazorPages and MVC controller with view.
And at then configure section
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Added above codes.
When I try to access to controller I am getting 404. I also tried to add just services.AddControllers();
need help please.
Edit : controller code
public class DashboardsController : BaseController, IDashboardsController
{
[HttpGet]
public async Task<JsonResult> GetAssetCategorySummaryAsync(){
-------
}
}
Your url should be localhost:9011/Dashboards/GetAssetCategorySummary.
You could modify the Startup.cs like below to allow using the whole action name:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.SuppressAsyncSuffixInActionNames = false;
});
services.AddControllersWithViews();
services.AddRazorPages();
}
It is a known issue on github,you could refer to here.
I can recommend my solution.
In Startup
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Create your CUSTOM base controller like that.
[Route("api/[controller]/[action]/{id?}")]
[ApiController]
public class CustomBaseController : ControllerBase
{
}
And use CustomBaseController
public class TestController : CustomBaseController
{
public IActionResult Test()
{
return Ok($"Test {DateTime.UtcNow}");
}
}
Rout` api/Test/test

Changing ASP Core default route to different controller

I cannnot get my ASP .NET Core MVC site to route to different controller other than Home. I changed the default route in Startup (it is the only route):
app.UseMvc(routes =>
{
routes.MapRoute(name: "default", template: "{controller=profile}/{action=index}/{id?}");
});
my ProfileController looks like:
public class ProfileController : Controller
{
[HttpGet("index")]
public IActionResult Index()
{
return View();
}
...
}
But all I get is 404 returned form the Kestrel server on navigating to base URL.
I've just created a new project and it worked for me. Maybe you're doing something else wrong.
Here's what I did.
Create a new asp.net core web application project (choose MVC template)
Update the default route in the Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
} else {
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=profile}/{action=index}/{id?}");
});
}
Create the Profile Controller:
public class ProfileController : Controller {
// GET: /<controller>/
public IActionResult Index() {
return View();
}
}
Create the Index View for the Profile Controller:
Run the project and the Profile's Index page should open.
UPDATE:
The problem was the [HttpGet("index")] in the Profile Controller.