asp.net core 3 routing - asp.net-core

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

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.

My razor pages are not working all of the generate the same error : Localhost page cant be found

This is my startup.cs file
Does anyone know whats going wrong This is my index.cshtml
Alright so my code will be below its very basic startup.cs file and a index.cshtml file with some basic code just for testing
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
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();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}}
#page
#DateTime.Now
Try to create a new project and check whether you have the same problem.
And did you apply something to your service side? You can share it.
Or you can try these code first:
ConfigureServices:
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
});
Configure:
app.UseMvcWithDefaultRoute();

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

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.