i wanted to change the launching url of the WebAPI from https://localhost:7027/controller to https://localhost:7027/test/controller. i have tried adding app.UsePathBase("/test") but it only routes swagger. i tried it with postman and it says 404 not found. how do i go about accomplishing this please. thank you
You can do that with attribute routing for a specific controller or
[Route("test/[controller]")]
public class ValuesController : Controller
{
Or globally you can do like below
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
See below - Change the "/api" part of the url in ASP.Net Core
Related
I have a .NET 6 ASP.net Core web application where I want to configure all calls with a particular path prefix to map to a specific controller.
What I want is for all calls that are of the form http://myhost/ipc/some_action to invoke the action some_action of the controller LocalIpcController. Here's how I setup my route in Startup class:
//Configure routing
app.UseEndpoints(endpoints =>
{
//Local IPC endpoint
endpoints.MapControllerRoute(
name: "Ipc",
pattern: "ipc/{action}",
defaults: new { controller = "LocalIpc" }
);
}
However, it is not working. Specifically:
If I make a call to http://myhost/ipc/some_action I get a 404 error
If I make a call to http://myhost/some_action it works correctly
So it looks like the /ipc prefix in the path is completely ignored. Why is this happening?
PS: I know I can also use the [Route] attribute on the controller to do this, but I want to why it isn't working via MapControllerRoute() and what I am doing wrong.
I tested it out and it is working for me. Here is the pipeline configuration and the test controller:
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Don't forget to use the UseRouting middleware.
app.UseRouting();
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseEndpoints( endpoints => {
//Local IPC endpoint
endpoints.MapControllerRoute(
name: "Ipc",
pattern: "ipc/{action}",
defaults: new { controller = "LocalIpc" }
);
});
Note: do not forget to include the app.UseRouting();
public class LocalIpcController : ControllerBase
{
public LocalIpcController()
{
}
[HttpGet]
public IActionResult Get()
{
return Content("I'm here.");
}
}
Also I would like to add, that defining the URL routes in endpoints middleware options is not in my opinion the best approach from readability perspective and I would use it only in some edge cases. It is much more clear to specify it in Route attribute (or you can even put it into HTTP method attribute constructor e.g. [HttpGet("ipc/some_action")]).
It turns out, I didn't understand properly how the routing attributes work in ASP.net.
In my controller, the action methods were marked like this:
[HttpGet("some_action")]
public IActionResult MyMethod()
{
}
I was under the impression that "some_action" would be appended to the path indicated in the configuration phase, to obtain "ipc/some_action", but apparently that is not the case, the route specified in the attribute seems to override the one specified in the MapControllerRoute() method.
How can I use attribute routing in the Home Controller, like
[Route("")]
[Route("Home")]
[Route("Home/Index")]
public IActionResult Index()
{
return View();
}
to get to the main page and not have
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
in Startup.cs?
If you use net core your startup could be like this:
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Whether you do not use attribute routing, you have to use endpoint. The endpoint is a mapping to the routing template.
When the first HTTP request comes in, the Endpoint Routing middleware will map the request to an Endpoint. It will use the EndpointDataSource created when the App starts, use it to traverse to find all available Endpoints, and check the routing and metadata associated with it in order to find the most matching Endpoint.
Once an Endpoint instance is selected, it will be attached to the requested object so that it can be used by subsequent middleware.
Finally, at the end of the pipeline, when the Endpoint middleware is running, it will execute the request delegation associated with the Endpoint. This request delegate will trigger and instantiate the selected Controller and Action methods, and generate a response. Finally, the response is returned from the middleware pipeline.
Take a look at the following flow chart.
About attribute routing, it improves the freedom of routing and also provides good support for restful api.
I am beginner in ASP .NET Core 2.1 and working on project which is using ASP .NET Core 2.1 with individual authentication. I want to make my login page as my default route instead of Home/Index:
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
Any help how can i change it as ASP .NET Core 2.1 as Login is now used as a razor page instead of MVC Action View.
Use this in ConfigureServices method.
services.AddMvc().AddRazorPagesOptions(options=> {
options.Conventions.AddAreaPageRoute("Identity", "/Account/Login","");
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
then in Configure method
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I solve this by using this code in ConfigureServices function (Startup.cs)
services.AddMvc().AddRazorPagesOptions(options => {
options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", "/Account/Login");
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
this may help, i haven't had a need to change default page myself
https://exceptionnotfound.net/setting-a-custom-default-page-in-asp-net-core-razor-pages/
Just use this in your configuration. This will add AuthorizeAttribute to your page
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Home/Index");
});
Or change the Default route like this :
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Employees/Index", "");
});
See this page if necessary : https://learn.microsoft.com/en-us/aspnet/core/security/authorization/razor-pages-authorization?view=aspnetcore-2.1
Insert this code to ConfigureServices() in Startup.cs
{
services.AddMvc().AddRazorPagesOptions(options =>
{
//Registering 'Page','route-name'
options.Conventions.AddPageRoute("/Account/Login", "");
});
}
Remember to remove any route name on "/Account/Login" Action declaration
After along time I solved it. Need add ALLOW for AREAS =>
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorPagesOptions(options =>
{
options.AllowAreas = true; //--working after add this line
options.Conventions.AddAreaPageRoute("Identity", "/Account/Login", "");
});
Add authorization policy so that application by default asks user for authentication for the pages under abc folder and does not ask for some public pages under abc folder.
services.AddRazorPages().AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/abc");
options.Conventions.AllowAnonymousToPage("/abc/PublicPage");
});
I had also in the same problem with my asp net core project which consists an API(asp net core web API) and a client(asp net core MVC), The problem I have faced when I published my project and tried to host it in my localhost it did not return me the login page which I have configured into the project startup.cs file the endpoint setting the default page I had set was "{controller=Account}/{action=Login}/{id?}" but localhost did not respond with this, after finding solution in the web I found some mechanism to do it but that solution doesn't suit me so I have made trick by my own and hope many net core developer would be helpful with my solution:
So the trick is I restore the previous configuration of end point as
"{controller=Home}/{action=Index}" and did a little change by removing "/{id?}" from the screen so the actual string was "
{controller=Home}/{action=Index}/{id?}
" and I have changed it to "{controller=Home}/{action=Index}" the logic is when program starts by default it will execute the default endpoint setting so program will take us to the controller which is "Home" and action is "Index" before returning the Index view I have checked a value "UserId" which must create upon login and kept it into a session variable,
var userid = _session.GetString("userid");
if (string.IsNullOrEmpty(userid))
{
return RedirectToAction("Login","Account");
}
This is how I solved my problem. The localhost and live publish also running fine, simply clicked view in browser and it returns the login page as my requirement.
Hope it helps.
Thanks
I'm creating an ASP.NET Core API app, and currently, and when one creates a new project there is a controller named Values, and by default the API opens it when you run. So, I deleted that controller and added a new controller named Intro, and inside it an action named Get. In the Startup.cs file, I have the following lines of code:
app.UseMvc(opt =>
{
opt.MapRoute("Default",
"{controller=Intro}/{action=Get}/{id?}");
});
And my Intro controller looks like this:
[Produces("application/json")]
[Route("api/[controller]")]
[EnableCors("MyCorsPolicy")]
public class IntroController : Controller
{
private readonly ILogger<IntroController> _logger;
public IntroController(ILogger<IntroController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
// Partially removed for brevity
}
}
But, again when I run the API, it by default tries to navigate to /api/values, but since I deleted the Values controller, now I get a 404 not found error. If I manually then navigate to /api/intro, I get the result that is provided from my Get action inside the Intro controller. How can I make sure that when the API run (for example through Debug->Start Without Debugging) that it by default gets the Get action from the Intro controller?
You can change it in launchSettings.json file in Properties node. There should be field launchUrl which contains default launching url
With later version of ASP .Net Core, MVC routing is less prominent than it once was, there is general routing now in place which can handle routing of Web APIs, MVC and SignalR amongst other kinds of routes.
If you are using later versions, and not specifically calling app.UseMvc you can do this with the generalised Endpoints configuration:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=Account}/{action=login}/{id?}");
// Create routes for Web API and SignalR here too...
});
Where Account and login are your new default controller and actions. These can be MVC or Web API controller methods.
I want to add the client name in each and every route in my .net core application. I do not want to add in each controller using Route OR RoutePrefix. It should be available for all controllers. So,how can I do this ?
Lets say I have following routes
mysite.com/virtualdir1/clientname/Login
mysite.com/virtualdir1/clientname/Dashboard
mysite.com/virtualdir1/clientname/Home
mysite.com/virtualdir1/clientname/AboutUs
I have tried to setup in startup.cs file as follows but it gives 404 error
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Backend",
template: "{clientname}/{controller=Home}/{action=Login}");
});
Thanks for the help !