ASP.NET - unable to find view - asp.net-mvc

There is a long-standing issue with ASP.NET MVC not properly handling URL routes if there are forward slashes as a parameter even if they are URL encoded.
Example:
On a default install, go to this URL (adjusting ports as needed)
http://localhost:11541/Token/Create?
callback=http%3a%2f%2flocalhost%3a11491%2ftoken%2fcreatetoken%2fAddPrivateValues
Notice that the Controller is "Token" and "Create" is the method to be called. This is the error I get:
The view 'http://localhost:11491/token/createtoken/AddPrivateValues' or
its master was not found or no view engine supports the searched
locations. The following locations were searched:
~/Views/Token/http://localhost:11491/token/createtoken/AddPrivateValues.aspx
~/Views/Token/http://localhost:11491/token/createtoken/AddPrivateValues.ascx
~/Views/Shared/http://localhost:11491/token/createtoken/AddPrivateValues.aspx
~/Views/Shared/http://localhost:11491/token/createtoken/AddPrivateValues.ascx
Notice that it's calling "CreateToken/AddPrivateValues". This is wrong. It should be calling Token.Create.
This issue appears to have been broken since 2009 (according to prior S.O. research) so I'm not holding my breath. I just need to fix this and move it to Azure.
I tried adding a {*id} route to my controller, but that doesn't work because there are many forward slashes. The only way to fix this is to disable this parsing in the machine.config (web.config WILL NOT WORK)
Question
How do I set this property in Windows Azure, without using RDP so that the permissions on Web.config are as secure and locked down as they were before I attempted to do this?

I am unable to replicate your issue on a clean deployment of an MVC 4 project. How are you trying to pass the callback parameter back to your view (if at all). If you are using
return View(callback);
This would be why it is failing, because it is interpreting the string variable as a view name. Try either storing it in a view bag or encapsulating it within a view model. As a side note, I know that passing parameters with slashes seems to work in all MVC versions since on the Account/Login controller action you can send a returnUrl without issue.
Below is my configuration, let me know if I have deviated anywhere from your setup.
Route Config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Changed default route to allow me to only have to create one controller
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Token", action = "Index", id = UrlParameter.Optional }
);
}
Token Controller
public ActionResult Index()
{
return View();
}
public ActionResult Create(string callback)
{
#ViewBag.Item = callback;
return View();
}
Create.cshtml
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#ViewBag.Item
My URL: http://localhost:11319/Token/Create?callback=http%3a%2f%2flocalhost%3a11491%2ftoken%2fcreatetoken%2fAddPrivateValues
My Create Page Results
<h2>Create</h2>
http://localhost:11491/token/createtoken/AddPrivateValues
<script src="/Scripts/jquery-1.8.2.js"></script>

Related

Hide url Controller and Action - Asp.NET MVC5

I would like to keep the same server url. ex: 10.139.183.192 to all pages.
I don't want to show 10.139.183.192/Task/Create
The route must continues, when the user type on address bar. But I want to hide it.
I've been searching a lot about url rewrite, but I can't find a solution.
I've tried to change the Global asax, Register Routes, etc.
Shoud I change in the IIS Server or in the Application?
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
You can work all pages on Home Controller and return View depending the post, exemple:
public ActionResult Home()
{
string page = Request["page"];
switch (page)
{
case "Home":
return View();
break;
case "Product":
return View("Product");
break;
default:
return View();
break;
}
return View();
}
or
User accesses all controllers and you code JS to change URL, like this:
window.onload = function(){
window.history.pushState("", "", "/");
}
You can only do that natively if you use a client side framework such a Angular.JS.
In C#.NET MVC5 only three ideas come to my mind.
Use AJAX to change the content of the page without going to an other page
Second, you use a home-made routing like #Rodolfo said
Third and last (this is the weirdest one), you call your pages not in GET but passing POST data (making a FORM for each link) so the base route can control the displayed content based on the form data. This allows you to always target the same URL 10.139.183.192, unlike the point just above where the URL would change (GET parameters).
Personally, I think that what you are trying to achieve should be done either with a dedicated client side frameworks (they were made for that, but it would be JavaScript, not C# I believe) or using the Ajax method.

How do I do Short URLs in MVC?

Suppose I want to publish (like in paper catalogs) some "short URLs" that are easy to type/remember, but I want them to redirect to a verbose, SEO-friendly URL. How do I accomplish that with MVC routes?
Example:
http://mysite.com/disney
becomes
http://mysite.com/travel/planning-your-disney-vacation (with "travel" as the Controller)
The things I've tried:
Just setup a route for it. Problem: the URL doesn't change in the browser (it stays "/disney".
Use NuGet package RouteMagic (see Haacked's article). Problem: I get an error: The RouteData must contain an item named 'controller' with a non-empty string value. I think this is because I don't have a static word before my controller ("travel") like he did (with "foo" and "bar")???
Use a redirect module (like Ian Mercer's). Problem: the route matches on my HTML.ActionLinks when creating URLs which I don't want (Haacked mentions this in his article and says that's why he has GetVirtualPath return NULL ...?)
I'm out of ideas, so any would be appreciated!
Thanks!
You could set up a catch-all type route, to direct all /something requests to a specific action and controller, something like:
routes.MapRoute(
"ShortUrls",
"{name}",
new {controller = "ShortUrl", action = "Index", name = UrlParameter.Optional}
);
(depending on how the rest of your routing is set up, you probably don't want to do it exactly like this as it will likely cause you some serious routing headaches - but this works here for the sake of simplicity)
Then just have your action redirect to the desired URL, based on the specified value:
public class ShortUrlController : Controller
{
//
// GET: /ShortUrl/
public ActionResult Index(string name)
{
var urls = new Dictionary<string, string>();
urls.Add("disney", "http://mysite.com/travel/planning-your-disney-vacation");
urls.Add("scuba", "http://mysite.com/travel/planning-your-scuba-vacation");
return Redirect(urls[name]);
}
}
I just faced the same problem.
In my Global:
routes.MapRoute(
"ShortUrls",
"{name}",
new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);
In my Home Controller:
public ActionResult Index(string name)
{
return View(name);
}
This way is dynamic, didn't want to have to recompile every time I needed to add a new page.
To shorten a URL you should use URL rewriting technique.
Some tutorials on subject:
url-rewriting-with-urlrewriternet
url-routing-with-asp-net-4
URL rewriting in .Net

RedirectToAction Causes "No route in the route table matches the supplied values" in ASP.NET MVC 3

I have a project that I recently upgraded to ASP.NET MVC 3. On my local machine, everything works fine. When I deploy to the server, I get an error anytime I use a RedirectToAction call. It throws a System.InvalidOperationException with the error message No route in the route table matches the supplied values. My assumption is that there is some configuration problem on the server, but I can't seem to be able to figure it out.
I ran into this with areas within MVC3 when redirecting across areas. As others have said, Glimpse is very useful here.
The solution for me was to pass in the Area within the route values parameter changing:
return RedirectToAction("ActionName", "ControllerName");
to:
return RedirectToAction("ActionName", "ControllerName", new { area = "AreaName" });
I had a similar problem once with RedirectToAction and found out that you need a valid route registered that leads to that action.
Check out glimpse and see if you can get some route debugging information:
http://getglimpse.com/
You could add a route table to your RouteConfig.cs file like below:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
var namespaces = new[] { typeof(HomeController).Namespace };
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("name", "url", new { controller = "controllerName", action = "actionName" }, namespaces);
}
NB: the "url" is what you'd type into the address bar say: localhost:/home
After setting up the route, use RedirectToRoute("url").
Or if you'd prefer the RedirectToAction() then you don't need to set up the above route, use the defaults.
RedirectToAction(string action name, string controller name);
I hope this helps.
There's a difference with trailing slashes in routes not working with MVC 3.0. MVC 2.0 doesn't have a problem with them. I.e., if you change the following:
"{controller}.mvc/{action}/{id}/"
to:
"{controller}.mvc/{action}/{id}"
it should fix this (from this thread, worked for me). Even when you use the upgrade wizard to move to MVC 3.0, this still throws InvalidOperationException. I'm not aware whether this is what Schmalls was talking about though.
In my case, default route was missing:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

404 asp.net mvc - beginner question in routing

This is a beginner level question for asp.net MVC
I have the following code in global.asax.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = (string)null } // Parameter defaults
);
}
in Homecontroller.cs i have updated the Index method as follows
public ActionResult Index(string id)
{
ViewData["Message"] = "Welcome to ASP.NET MVC1!"+ id;
return View();
}
My understanding is, if I give the url http://localhost/mvc1/default/1 it should work
instead it is throwing up 404 error
any help what is the reason behind this
I'm assuming your application is called "mvc1" and that's the root of your project. If that's the case:
So "default" is the name if your route, not the name of the action. Basically what the routing engine does is look for a controller and action that matches requests coming in. Given the route you have setup, it would break down like this:
http://localhost/MVCApplication1/default/1
(cont) (action)
If certain parts of the route are omitted, it will attempt to fill in the missing values with the defaults you have specified. As you can see, there is no controller named DefaultController in your project, and thus it uses the default you've specified which is Home. It then tries to find an action method called default and fails again, so it uses the default value in your route, which is Index. Finally, you have 2 segments left in your URL, and no route matches that pattern (2 segments after the action), so it can't find the right place to go.
What you need to do is remove one of your segments, and this should work. Routing can be a little tricky, so I would recommend reading up on it.
The URL you're requesting is asking for a controller called "mvc1" and an action called "default" which will receive an id of "1". Since you don't have a controller named "mvc1" (I assume?), you're getting the 404 error.
The defaults for controller and action are only used if controller and action aren't provided. Since you provided controller and action, MVC is looking for them specifically.

ASP.NET MVC App Routing Not Working For Dynamic Data WebForm Pages

I need the correct Global.asax settings in order for my Dynamic Data site to run under an ASP.NET MVC project. The routing currently appears to be my issue.
Here is my global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
MetaModel model = new MetaModel();
model.RegisterContext(typeof(Models.DBDataContext), new ContextConfiguration() { ScaffoldAllTables = true });
routes.Add(new DynamicDataRoute("DD/{table}/{action}.aspx") {
Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
Model = model
});
routes.MapRoute(
"Assignment",
"Assignment/{action}/{page}",
new { controller = "Assignment", action = "Index", page = "" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Admin", action = "Index", id = "" }); // Parameter defaults
}
Link that I'm trying to use is:
http://localhost:64205/DD/Work_Phases/ListDetails.aspx
I am getting the following message:
Server Error in '/' Application. The
resource cannot be found. Description:
HTTP 404. The resource you are looking
for (or one of its dependencies) could
have been removed, had its name
changed, or is temporarily
unavailable. Please review the
following URL and make sure that it is
spelled correctly.
Requested URL:
/DD/Work_Phases/ListDetails.aspx
I've tried replacing DD with DynamicData since the folder inside of the app is DynamicData and that yielded the exact same result.
The URL
http://localhost:64205/DD/Work_Phases/ListDetails.aspx
is matching your second (default) route, which is trying to hit a controller called "DD".
You may need another route entry that looks something like this:
routes.MapRoute(
"DD",
"DD/{action}/{page}",
new { controller = "NameOfController", action = "Index", page = "" }
);
...although I can't imagine why you would need to pass a page parameter. The page view that is hit depends on the return action of the controller method.
For a better look at integrating Dynamic Data with ASP.NET MVC, have a look at Scott Hanselman's Plugin-Hybrids article. He has some details about handling the .ASPX files that are not part of MVC. In particular, if you have an .ASPX that you don't want to be processed by the ASP.NET MVC controllers, you can install an Ignore Route:
routes.IgnoreRoute("{myWebForms}.aspx/{*pathInfo}");
It should be noted that ASP.NET MVC is configured out of the box to ignore URL requests for files that physically exist on the disk, although Scott's IgnoreRoute technique is apparently more efficient.
The url doesn't match your dynamic data route because it doesn't fit the constraints you put on it. You're requesting action ListDetails but only these actions are allowed
Constraints = new RouteValueDictionary(
new { action = "List|Details|Edit|Insert" }
EDIT: are you sure that an action called ListDetails exists? Then modify the constraints above to
Constraints = new RouteValueDictionary(
new { action = "ListDetails|List|Details|Edit|Insert" }
Just to be sure that it's the constraints that's causing the route to be ignored, can you try one of the default actions? E.g.
http://localhost:64205/DD/Work_Phases/List.aspx
For ASP.NET MVC to work, you will have to match the URL you are trying to access with the list of routes.
For your current global.asax, example of valid URLs are:
http://domain/AnyController/AnyAction/AnyParameter
http://domain/Assignment/
http://domain/Assignment/AnyAction/AnyParameter
MVC requests are redirected to the proper Controller class, Action method, with parameters as passed in. MVC request is not redirected to any ASPX class. This is the difference between ASP.NET MVC and vanilla ASP.NET Page.

Resources