ASP.Net Core MVC Project cannot configure routes? - asp.net-core

I recently started learning ASP.Net Core to develop a MVC Web API. But I cannot even get my hello world running.
In the Startup.cs I wrote:
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
services.AddMvc(routes =>
{
routes.MapRoute(
"default",
"{version?}/{controller=Home}/{action=Index}/{id?}");
});
}
And the console says:
error CS1929: 'MvcOptions' does not contain a definition for 'MapRoute' and the best extension method overload 'MapRouteRouteBuilderExtensions.MapRoute(IRouteBuilder, string, string)' requires a receiver of type 'IRouteBuilder'

Routing You have to add in Configure method not ConfigureService. Try this sample.
Here add mvc to service
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
Here set routes
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

Related

starup file changes in Asp.net core

I am Upgrading .Net core web api solution 2.2 to 3.1
I have question what should i use in statrup.cs file for 3.1
// currently i am using this
public Startup(Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
public Startup(Microsoft.Extensions.Hosting.IHostingEnvironment env)
I am Upgrading .Net core web api solution 2.2 to 3.1 I have question what should i use in statrup.cs file for 3.1
If you create a new ASP.NET Core 3.1 API project using the API template, you would find it uses below Startup class.
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();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Compare it with old one, you can find the following changes:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2) is changed to services.AddControllers()
IHostingEnvironment is obsolete, and it uses IWebHostEnvironment now
app.UseEndpoints, endpoint routing is used

How to set default razor page route with asp.net 3.0 middleware

So to setup endpoint routing in asp.net core 3.x, we do something like this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
});
}
How/where can we define a "default" page route other than index?
The easiest solution would be to manually add route to the custom page in ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages(o => o.Conventions.AddPageRoute("/CustomPage", ""));
}
With this solution you need to rename or remove Index page to avoid AmbiguousMatchException
This is an example of a default route.
app.UseEndpoints(endpoint =>
{
endpoint.MapDefaultControllerRoute();
});

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

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);
}