ASP.NET Core WebAPI default route not working - asp.net-core

I've followed several examples suggesting that to set my default route in an ASP.NET Core WebAPI project, I need to replace
app.UseMvc();
with
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}",
defaults: new { controller = "Traders", action = "Get" });
});
But when I run it defaults to localhost:54321/api/values and it should default to localhost:54321/Traders
What's wrong?

As #tmg mentioned, do the following:
Right click your web project -> Select Properties -> Select the Debug tab on the left -> Then edit the 'Launch Url' field to set your own default launch url.

You can change the default route by modifying LaunchSettings.json file as shown

Follow the steps below.
Create a base controller for your API that extends base controller of dotnet core:
using Microsoft.AspNetCore.Mvc;
namespace WebApi.Controllers
{
[Route("api/[controller]")]
public abstract class ControllerApiBase : Controller
{
}
}
And inherit the base class in your API controllers:
using Microsoft.AspNetCore.Mvc;
using WebApi.Dtos;
namespace WebApi.Controllers
{
public class PingController : ControllerApiBase
{
public PingDto Get()
{
return new PingDto
{
Version = "0.0.0"
};
}
}
}

Related

Configurable route prefix for controller

I'm using ASP.NET Core 6 and trying to have the base path of my API controller be configurable (so that users can choose the base path themselves to avoid conflicts with other controllers).
I tried setting up the following route:
string configurablePrefix = "/temp";
endpoint.MapControllerRoute(
name: "MyRouteName",
pattern: configurablePrefix + "/{action=MyDefaultAction},
defaults: new { controller = "MyController" });
Where MyController is defined like this:
[ApiController]
public class MyController : ControllerBase
{
[HttpGet("MyDefaultAction")]
public IActionResult MyDefaultAction()
{
return new JsonResult("Hello");
}
}
This causes no errors during startup, but when I access `https://localhost/temp/MyDefaultAction I get a 404
How can I get this to work so that actions in MyController are accessible on whatever start path the user chooses (i.e. change it to respond to /othertemp/MyDefaultAction instead)?
From your code, you are using ApiController, which cannot be routed by setting the corresponding route in Startup.cs or Program.cs.
ApiController must have attribute routing, and attribute routing has a higher priority than conventional routing, so it will override the conventional routing you defined.
You can choose to use attribute routing to define the controller name as temp, so that the corresponding endpoint can be matched in ApiController:
[Route("temp")]
[ApiController]
public class MyController : ControllerBase
{
[HttpGet("MyDefaultAction")]
public IActionResult MyDefaultAction()
{
return new JsonResult("Hello");
}
}
Test Result:
Or use an MVC controller:
public class MyController : Controller
{
[HttpGet]
public IActionResult MyDefaultAction()
{
return new JsonResult("Hello");
}
}
Routing:
string configurablePrefix = "/temp";
endpoint.MapControllerRoute(
name: "MyRouteName",
pattern: configurablePrefix + "/{action}",
defaults: new { controller = "My", action = "MyDefaultAction" });
Test Result:
reference link: Create web APIs with ASP.NET Core.

.NET Core 3.1 MapControllerRoute causing urls without areas to not load properly

I have these 2 route patterns:
config.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{Controller=Home}/{Action=Index}/{id?}");
config.MapControllerRoute(
name: "default",
pattern: "{Controller=Home}/{Action=Index}/{id?}");
Since my application mainly uses areas, all of the urls with areas work fine.
Example:
[Area("Configuration")]
[TypeFilter(typeof(ValidateAdministratorFilter))]
public class ApiKeyApplicationController : Controller
{
public ActionResult Index()
{
}
}
The above URL will look like this in a #Url.Action: /Configuration/ApiKeyApplication/Index only
However, if I have a url without an area, like this:
[Route("/[controller]")]
[Authorize]
public class ConfirmController : Controller
{
public ActionResult ConfirmDetails()
{
return View("~/Views/Modals/ConfirmDetails.cshtml");
}
}
The above URL will look like this in a #Url.Action: /Confirm only
If I try to set it to /Confirm/ConfirmDetails, it will show a 404 error
Is this due to my routing?
You just need to delete the route in your ConfirmController
Delete this :
[Route("/[controller]")]
Or you can change it to:
[Route("[controller]/[action]")]

asp.net core maproute template with string concatenate to action

I have a HelloController
When i input URL with http://localhost/Hello/1234
How Could i link to the W1234
I try to modify maproute template like
template: {controller}/W{action}
But it didn't work
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Hello",
template: "{controller}/{action}/{id?}");
});
public partial class HelloController : Controller
{
public IActionResult W1234()
{
return View();
}
}
You could try to use Attribute routing uses a set of attributes to map actions directly to route templates.
[[Route("Hello/1234")]
public IActionResult W1234()
{
return View();
}
Attribute routing can also make use of the Http[Verb] attributes such as HttpPostAttribute. All of these attributes can accept a route template.
[HttpGet("/Hello/1234")]
public IActionResult W1234()
{
return View();
}
Reference : Routing to controller actions in ASP.NET Core

Can I override the default action for a single controller in ASP.Net Core MVC

Is it possible to override the default action for a single controller without affecting the rest of the routing?
I currently have a default route of
routes.MapRoute(
name: "Default",
template: "{controller}/{action}",
defaults: new { controller = "Book", action = "Index" }
);
This works in the general case but I now want to add an AdminController, but I want the default action on AdminController to be Users, instead of Index.
I don't really want to use attribute routing on this controller as we may later update the default routing and I want to keep as much as possible centralised and DRY. I just want the urls /Admin and /Admin/Users to route to the Users action in this one controller.
I'm currently using ASP.Net Core 2.0 with the intention to move to 2.1 as soon as it is released. It's currently running on .Net Framework but we want to upgrade to .Net Core as soon as we can get rid of some dependencies we currently have on the framework (unlikely to be for the first release).
Any suggestions?
While more intensive than using attribute routing you can do
routes.MapRoute(
name: "AdminDefault",
template: "Admin/{action}",
defaults: new { controller = "Admin", action = "Users" }
);
routes.MapRoute(
name: "Default",
template: "{controller=Book}/{action=Index}",
);
using Attribute routing on the controller it would have been
[Route("[controller]")]
public class AdminController : Controller {
[HttpGet]
[Route("")] //Match GET admin
[Route("[action]")] //Match Get admin/users
public IActionResult Users() {
return View();
}
}
Or even
[Route("[controller]/{action=Users}")]
public class AdminController : Controller {
[HttpGet]
public IActionResult Users() {
return View();
}
}
Reference Routing to Controller Actions in ASP.NET Core
Please check below code:
routes.MapRoute(
name: "Admin",
template: "{controller}/{action}",
defaults: new { controller = "Admin", action = "Users" }
);

Visual Studio MVC4 Auto Url Routing for All Url's

Hello everyone I am working with VS13 MVC4 in localhost, for url routing I want VS will work for all url's automatically as www.sitename.com/about-us but now it is getting underscore (_) not dash (-) how to make a change and get hyphen(-) before every new word in url
Here is the answer I also add it to my question for everyone can see:
public class HyphenatedRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
return base.GetHttpHandler(requestContext);
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(
new Route("{controller}/{action}/{id}",
new RouteValueDictionary(
new { controller = "Default", action = "Index", id = "" }),
new HyphenatedRouteHandler())
);
}
}
Thanks everyone.
If you want pretty url in asp.net mvc then you should go by registering new route for your controller.
from the application directory open RouteConfig.cs in the App_Start directory.
And in the RegisterRoutes method of RouteConfig class register a new route like this-
routes.MapRoute(
name: "AboutUs",
url: "sitename/about-us",
defaults: new { controller = "About_Us", action = "Index" }
);
The _ will prob be automatically converted to a - in the routing. The other way is to set up the routing yourself