I am working on a C# mvc application. In my site I have this url abc.com/About/WhoWeAre, where 'About' is the Controller and 'WhoWeAre' is the action name. But i want this url to be returned as abc.com/About/who-we-are. The problem is I can't name the action containing '-' in it. I tried Url Redirection using HttpContext Response but couldn't find a solution.
If I handle the request in Route Config for 'About/who-we-are' and route it to 'About/WhoWeAre' it is working with the required url in the address bar. But when I make request for 'About/WhoWeAre' it returns the page with the same('About/WhoWeAre') url in the address bar, which duplicates the url. How can I redirect?
Feel free to ask any questions.
Use ActionName Attribute to map the Url. Below is the example
public class AboutController : Controller
{
[ActionName("Who-we-are")]
public ActionResult WhoWeAre()
{
return View();
}
}
You can use the ActionName attribute to rename your actions with characters that are disallowed in C# method names.
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 call a POST method in react but at the end I want to get redirected to the root url of my application.
I have this code where I'm trying to redirect to the root url (localhost:50000) , but it doesn't do anything
I also tried doing Redirect("http://localhost:50000") and it also doesn't work. I tried testing with google.com and I get a serverside error, basically I can't redirect to any website.
[Route("api/[controller]")]
[ApiController]
public class EntityBuilderController : ControllerBase
{
[HttpPost("[action]")]
public ActionResult CreateEntity(string xmlPath, string dllPath)
{
DataMapper.ExtractEntities(xmlPath, dllPath);
return Redirect(Url.Content("~/"));
}
}
Update: after seeing the questioner original code through remote access I have found that questioner application is a ASP.NET Core React SPA.
You cannot redirect from API controller to your client app view. You have to do the redirection from your client app on successful entity creation.
Are you sure using [ ] instead of { } in your route naming convention? Check it out here
[Route("api/[controller]")]
//if you are replacing controller name then it should be
[Route("api/{controller}")]
I have a MVC website in which I would like to have a website URL hit and then depending on the parameters passed in, display the native phone interface, email interface, or SMS interface.
I can get each of the interfaces on a smartphone by typing in the interface in a web browser. For example if I go into safarai on iphone and type tel:55555555 the phone prompt will appear with 55555555 filled in.
How could I redirect to the interfaces from an MVC controller?
Add a controller action to your controller that calls Response.Redirect with the appropriate protocol. For example:
public class HomeController : Controller
{
public ActionResult Phone()
{
Response.Redirect("tel:5551212");
return new EmptyResult();
}
}
When this controller action is hit, it prompts the browser to redirect and attempt to open the phone app. In my case, it opens Skype. You can modify your controller action, of course, to redirect using different protocols based upon parameters.
The URL to call this controller action is simply http://whatever/home/phone. You can also shorten this controller action to:
public ActionResult Phone()
{
return Redirect("tel:5551212");
}
That is a little prettier, in my opinion. There is a similar question answered here:
In ASP.NET MVC, how does response.redirect work?
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.