I've been trying to create a link that includes the subdomain to look like this batman.website.com, but instead it generates this website.com/?subdomain=batman
I'm generating the link through this method
#Html.RouteLink("Link", new { controller = "home", subdomain = activity.From.Username, id = activity.PostId, action = "post" })
and my routing routeconfig class looks like this
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new SubdomainRoute());
}
}
the subdomain route is heavily based off of this http://benjii.me/2015/02/subdomain-routing-in-asp-net-mvc/
Could someone point me in the right direction to format the link correctly
If you're using MVC for authentication, you could do something like this, straight into the view:
Test Link
Another way (if your authentication isn't based on MVC) would be to set the username at the View Controller on the ViewBag and then set it to display in the view:
Controller:
ViewBag.VarName = userName;
View:
Test Link
Another question that gives more detail and examples:
How to get current user, and how to use User class in MVC5?
Hopefully some of this points you in the right direction!
Related
I have two controllers, one Web API controller and the other a MVC controller. These two controllers have the same name and the same action name, though the one in API controller is a post while the one in MVC is a get, as shown here.
This is the API controller:
[Route("api/[controller]")]
public class SameNameController : ControllerBase
{
[HttpPost]
public IEnumerable<*className*> SameNameAction([FromBody] *typeName*[] data)
{
// Detail implementation
}
}
And this is the MVC controller:
public class SameNameController: Controller
{
public ActionResult SameNameAction(int? page, int? pageSize)
{
//Detail implementation
}
}
I'm using X.PagedList to generate pagination. When I click any of pages, I receive an error
HTTP 405 - this page isn't working
Upon further inspection, I realized that the URL generated is the issue.
Here is the problematic part of the view.
#Html.PagedListPager((IPagedList)Model, page => Url.Action("SameNameAction", "SameNameController", new { page, pageSize= 5}))
Here is the routing definition in program.cs. As you can see, it's just basic stuff.
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
I expect that Url.Action would generate an url to the get action of the MVC controller. Instead, it generates an url to the post action of the Web API controller.
This is what I got:
2
This is what I expect:
2
I've never experienced Url.Action generating routing to an API controller. I'm not sure this is due to pagelist combined with url.action or url.action alone.
I can change the action name of the API controller, and the URL is generated as expected. However, this is not the issue. I would like to know why it map to the API controller and not the MVC controller to begin with.
I expect that Url.Action would generate an url to the get action of
the MVC controller. Instead, it generates an url to the post action of
the Web API controller.
Based on your scenario, I have checked your code between the line. As you know \[Route("")\] Attribute always has the higher precedence in routing therefore, this output/api/SameNameController?page=2&pageSize=5is obvious. However, using Url.RouteUrl HTML helper you can overcome your issue.
Solution:
#Html.PagedListPager((IPagedList)Model, page => Url.RouteUrl("default", new{httproute = "", controller="SameName",action="SameNameAction",page=1, pageSize= 5}))
Note: Please fit the code as per your environment.The exact code should be as folloing:
#Url.RouteUrl("default", new{httproute = "", controller="SameName",action="SameNameAction",page=1, pageSize= 5})
Output:
Hope it will guide you accordingly.
I have an Administration Controller with a Users method. And I would like to add a “new” Subaction with a new View to this method. The URL should look like this: /administration/users/new
How can I do that?
Thanks for your help!
This is really just a question about routing. Just add a method in the Administration controller and tell MVC what the route is with a Route attribute. For example:
public class AdministrationController : Controller
{
public ActionResult Users()
{
}
[Route("users/new")] //This is the important part here
public ActionResult NewUser()
{
}
}
You could also configure the routing inside your Startup.cs class, but I find it easier to do with attribute routing. See here for more information.
I guess what you mean is "Area".
So, in Asp.Net Core 2 routing, there are areas, there are controllers, there are actions and optionally parameters.
You can have routing middleware configured something like. You can specify area attribute on the contorllers.
Administrator would be area - Users would be controller and New would be action.
This should keep the code clean as this is merely using the default routing middleware.
For better understanding of Areas, please refer: https://tahirnaushad.com/2017/08/25/asp-net-core-2-0-mvc-areas/
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller=dashboard}/{action=index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=home}/{action=index}/{id?}"
);
You can use several methods to do it
Routes at .net core
try attributes
[Route("users/new")]
public IActionResult New()
{
return View();
}
So I have a HomeController, to access it along with Actions I have to type url.com/home/action.
Would it be possible to change this to something else like url.com/anothernamethatpointstohomeactually/action?
I suggest you to use attribute routing, but of course it depends on your scenario.
[Route("prefix")]
public class Home : Controller {
[HttpGet("name")]
public IActionResult Index() {
}
}
This will be found at url.com/prefix/name
There are a lot of options to attribute routing, some samples:
[Route("[controller]")] // there are placeholders for common patterns
as [area], [controller], [action], etc.
[HttpGet("")] // empty is valid. url.com/prefix
[Route("")] // empty is valid. url.com/
[HttpGet("/otherprefix/name")] // starting with / won't use the route prefix
[HttpGet("name/{id}")]
public IActionResult Index(int id){ ... // id will bind from route param.
[HttpGet("{id:int:required}")] // you can add some simple matching rules too.
Check Attribute Routing official docs
You can add new Routes in your Startup.Configure method within your app.UseMvc(routes => block:
routes.MapRoute(
name: "SomeDescriptiveName",
template: "AnotherNameThatPointsToHome/{action=Index}/{id?}",
defaults: new { controller = "Home"}
);
The code is quite similar to ASP.NET MVC.
For more info, see Routing in ASP.NET Core.
Below is for ASP.NET MVC (not ASP.NET Core MVC)
You can also add a new Route via routes.MapRoute in your RouteConfig:
routes.MapRoute(
name: "SomeDescriptiveName",
url: "AnotherNameThatPointsToHome/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Make sure, you insert the code before you define your Default route.
For more information, visit the docs.
Using the Route attribute on top of your controller will allow you to define the route on the entire controller.
[Route("anothernamethatpointstohomeactually")]
You can read more here.
In ASP.NET Core 6, we just do that in one line.
Go to your Controller and write before your action method:
[Route("YourController/YourAction/{YourParameter?}")]
In your example, you you need to write like this:
[Route("Home/Index/{name?}")]
You can change your url by modifying your routing configuration.
It is kind of like htaccess but not really.
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs
Another solution is to create a page and do a server redirect.
Server.Transfer
I have upgrade aspx project to mvc. Now some of my old customer calling url with .aspx page and they are getting 404(not found) in mvc project.
So now I have to redirect .aspx to mvc page.
Old URL
www.domain.com/bookshop/pc-58573-53-{product_name}.aspx
New URL
www.domain.com/{product_name}
I am thinking to do via routing mechanism of mvc. like once this type of url come then it should be call my custom mvc action and in string parameter i will get pc-58573-53-{product_name}.aspx
Can you please suggest a best way to do this with minimal code.
Just define an action with route 'bookshop/{pageName}'
Here are examples for 2 scenarios using Route attribute:
In case, you don't want the URL to change:
[Route("bookshop/{pageName}")]
public ActionResult MyAction(string pageName)
{
// add logic according to what you receive in pageName property
return View();
}
or, In case you want to Redirect to a new URL:
[Route("bookshop/{pageName}")]
public ActionResult MyAction(string pageName)
{
// Create and use a method to ExtractProductNameFromPageName
string productName = ExtractProductNameFromPageName(pageName);
return Response.Redirect("~/" + productName);
}
The parameter 'pageName' here should catch the page name past 'bookshop/'.
In case, you don't have route attribute mapping enabled, add code below in RegisterRoutes method of RouteConfig.cs file:
// enable mapping of routes defined using Route attribute on specific actions.
routes.MapMvcAttributeRoutes();
I am new in mvc and I have a situation where I am convinced that I am mapping a route correctly although it is not.
it is a very basic login form with the option of passing in parameters.
this is the html
<li>Login</li>
and this is the action method in the 'Home' controller
public ViewResult LoginForm(string userName)
{
return View();
}
This is how is my attempt at mapping the route
routes.MapRoute(
null,
"Login/{userName}",
new { controller = "Home ", action = "LoginForm", UrlParameter.Optional }
);
The url is however displaying as follow
/Home/LoginForm?loginUser=user
my aim would be the following
Login/user
Advice perhaps as to why it is not mapping correctly. I have already registered a number of routes in the Global.asax.cs file. Could it have something to do with the order with which they were registered?
Try this:
<li>Login</li>
change the parameter loginUser to userName.
Use userName instead of loginUser
<li><a href='#Url.Action("LoginForm", "Home", new {userName="user"})'>Login</a></li>
You are hitting a different address than the one specified in MapRoute. The mapped route will not fire. Change both the parameter and the action name.
<li>Login</li>
You need to access /Home/Login not /Home/LoginForm. The routing is done automatically if the right address is accessed.
EDIT:
Following your address edit:
As far as I know, you cannot generate a link such as Login/{userName} using Url.Action; if you don't specify a controller, this defaults to Home controller
You can however access the Login/{userName} link directly from the browser (due to the mapped route)
You can create a "static" (i.e. classic) link, passing a hard-coded address:
<li>Login</li>
Please note that the userName added/removed per JavaScript.