Changing ASP Core default route to different controller - asp.net-core

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.

Related

Razor View Does Not Display Records

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.

OData integration with CosmosDb does not return expected result

I have created a .NET Core 3.1 WebAPI application which connect with Azure Cosmos Db. The WebAPI is returning data from CosmosDb correctly. When I tried to integrate OData to this solution, and tried to query data using the Select method, it does not return expected result.
The following are my code:
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.AddOData();
services.AddControllersWithViews();
services.AddSingleton<ICosmosDbService>(InitializeCosmosClientInstanceAsync(Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());
}
// 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.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=ToDo}/{action=Index}/{id?}");
endpoints.EnableDependencyInjection();
endpoints.Select().Filter().OrderBy().Expand();
});
}
}
WebAPI controller:
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ItemsController : ControllerBase
{
private readonly ICosmosDbService _cosmosDbService;
public ItemsController(ICosmosDbService cosmosDbService)
{
_cosmosDbService = cosmosDbService;
}
// GET: api/<ItemsController>
[HttpGet]
[EnableQuery()]
public async Task<IEnumerable<Item>> Get()
{
return await _cosmosDbService.GetItemsAsync("SELECT * FROM c");
}
}
When I try to retrieve data using the API call(https://localhost:44357/api/items), I am getting expected result:
[{"id":"5f4f5d02-9217-4591-8f8c-2af9fe7d9ae4","name":"Brush","description":"Brush your teeth every night","completed":true,"partitionKey":null},{"id":"6a5edfe3-9c84-4398-bed4-963dbb4a42e3","name":"Excercise","description":"Hit the gym in the evening","completed":true,"partitionKey":null}]
But when I try to use the OData method(https://localhost:44357/api/items?$select=name), I am not getting expected result. Instead, I am getting this:
[{"instance":null,"container":{},"modelID":"7c0ae376-1666-46f8-886f-9bf758824063","untypedInstance":null,"instanceType":null,"useInstanceForProperties":false},{"instance":null,"container":{},"modelID":"7c0ae376-1666-46f8-886f-9bf758824063","untypedInstance":null,"instanceType":null,"useInstanceForenter code hereProperties":false}]
Any idea why it is like this?
There is incompatible situation with the JSON serializer in Asp.Net 3.1. Try to AddNewtonsoftJson.
services.AddControllers(mvcOptions =>
mvcOptions.EnableEndpointRouting = false)
.AddNewtonsoftJson();

ASP.NET core Web API routing

Route using "UseMvc" but not able to call the controller
In startup page have added service.AddMvc method & in configure section it's app.useMvc()
I am not able to route and can't figure out what the problem is
The controller code is here and have route : the action method is Get with parameter start of DateTime type
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CurrencyContext>(cfg => {
cfg.UseSqlServer(_config.GetConnectionString("BitCoinIndexConnectionString"));
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseNodeModules(env);
app.UseMvc(routes =>
{
routes.MapRoute(name: "default",
template: "api/{controller}/{action}/{start:DateTime}",
defaults: new {
controller = "Currency",
action = "Get",
start = DateTime.Now.AddDays(-14)});
});
}
}
[Route("api/[Controller]")]
public class CurrencyController : Controller
{
private BitCoinRepository<BitCoinIndex> _repository;
public CurrencyController(BitCoinRepository<BitCoinIndex> repository)
{
_repository = repository;
}
// GET: api/<controller>
[HttpGet("{start}",Name ="Get")]
public IActionResult Get(DateTime start)
{
// var bci = _repository.GetByDates(start).ToDictionary(t => t.Date.ToString(), t => t.Rate);
return View();
}
}
I faced the same issue and resolved it using attribute routing. This is what I did. If you are not using .Net Core 3, ignore point 1.
1st disable endpoint routing by adding this in your ConfigureServices:
services.AddMvc(options => options.EnableEndpointRouting = false);
You can now use this in Configure method
app.UseMvc();
Next, just define your routes inside the controller (bear in mind I generally prefer routing by adding routes to the routing table, but encountered unnecassary issues going this 'route', attribute routing was the easiest 'route' to take).
[Route("api/myctrl")]
[ApiController]
public class MyControllerController : ControllerBase
{
[HttpGet]
[Route("getsomething")]
public async Task<JsonResult> DoStuff()
{
}
}
Access this by either using #Url.Action("DoStuff", "MyController"); or /api/myctrl/getsomething

with asp.net core and ef core when i try to seed there went wrong

My startup.cs is
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?}");
});
SeedData.Seed(app);
}
and my seed class is :
public static class SeedData
{
public static void Seed(IApplicationBuilder app)
{
var _dbContext= app.ApplicationServices.GetRequiredService<BlogDbContext>();
_dbContext.Database.EnsureDeleted();
_dbContext.Add<User>(new User { UserName = "Niko", Password ="123",EmailAddress="nikozhao5456#gmail.com",UserType= Models.User.Type.Visitor,RegistDate=System.DateTime.Now});
_dbContext.Add<Admin>(new Admin{EmailAddress="lovezgd888#163.com",Password="123"});
_dbContext.SaveChanges();
}
}
when I Update-Database in the Nuget Package Manage :
An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Cannot resolve scoped service 'Blog.DAL.Context.BlogDbContext' from root provider.
and
Unable to create an object of type 'BlogDbContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
Well Ive solve it by watching the docs,There is something different between Asp.Net Core 1.x and 2.0;I just should write the seed method in the program.cs

Add custom query parameter to action URL in ASP.NET Core MVC

In ASP.NET Core MVC, I'd like to make it so that URLs created with Url.Action and action-based tag helpers include a custom query parameter in the URL. I want to apply this globally, regardless of the controller or action.
I tried overriding the default route handler, which worked at one time, but broke with an ASP.NET Core update. What am I doing wrong? Is there a better way?
Try adding it to the collection instead of overriding the DefaultHandler. The following worked for me on version 1.1.2:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// ... other configuration
app.UseMvc(routes =>
{
routes.Routes.Add(new HostPropagationRouter(routes.DefaultHandler));
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// ... other configuration
}
Here's the router, just for completeness.
public class HostPropagationRouter : IRouter
{
readonly IRouter router;
public HostPropagationRouter(IRouter router)
{
this.router = router;
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
if (context.HttpContext.Request.Query.TryGetValue("host", out var host))
context.Values["host"] = host;
return router.GetVirtualPath(context);
}
public Task RouteAsync(RouteContext context) => router.RouteAsync(context);
}