Can't find Controller in MVC 3 project - NotFound error - asp.net-mvc-3

I have this global.asax file with this code:
routes.MapRoute("Invitations",
"api/invitations",
new { controller = "Invitations", action = "Invitation"});
And I have a Controller:
public class InvitationsController : Controller
{
[HttpPut]
public JsonResult Invitation(InvitationResponse invitationResponse)
{
//code
}
}
And I'm accessing the controllers by HttpWebRequest with this URL:
"http://localhost:6055/API/Invitations"
When I run this I get the error "NotFound".
EDIT:
The whole global route:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Users",
"api/users/{id}",
new { controller = "Users", action = "UserAction", id = UrlParameter.Optional });
routes.MapRoute("CheckIn",
"api/checkins",
new { controller = "CheckIn", action = "CheckIn" });
routes.MapRoute("Appointments",
"api/appointments/{id}",
new { controller = "Appointments", action = "Appointment", id = UrlParameter.Optional });
routes.MapRoute("UserAppointments",
"api/users/{userId}/appointments/{startDate}",
new { controller = "Appointments", action = "UserAppointments", startDate = UrlParameter.Optional });
routes.MapRoute("UserInvitations",
"api/users/{userId}/invitations",
new { controller = "Invitations", action = "UserInvitations" });
routes.MapRoute("UserOverview",
"api/users/{id}/overview",
new { controller = "Users", action = "Overview" });
routes.MapRoute("Invitations",
"api/invitations",
new { controller = "Invitations", action = "Invitation"});
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

"http://localhost:6055/API/Invitations" doesn't look correct, shouldn't it be
"http://localhost:6055/YourApp/API/Invitations"

Related

mvc3 URL routing without action

I have a controller named article and my articles in the url take the shape of {controller}/{action}/{id}/{title}/{mixed} how can i get that to {controller}/{id}/{title}/{mixed}
my route value is
routes.MapRoute(
"articles",
"{controller}/{action}/{id}/{stitle}/{mixed}",
new { controller = "article",action="detail",mixed= UrlParameter.Optional} // Parameter defaults
);
I have tried this
routes.MapRoute(
"articles", // Route name
"{controller}/{id}/{title}/{mixed}",
new { controller = "article",action="detail",mixed= UrlParameter.Optional}
);
but get a 404 error
as my links are in the form
#Html.ActionLink("My article", "detail", "article", new { id = item.ArticleID, title = item.title, mixed = item.mixed })
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"ArticleWithoutAction", // Article Without Action name
"{controller}/{id}/{name}",
new { controller = "Article",
action = "detail",
id = UrlParameter.Optional,
title = UrlParameter.Optional,
mixed = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"ArticleWithAction", // Article With Action name
"{controller}/{action}/{id}/{name}",
new { controller = "Article",
action = "detail",
id = UrlParameter.Optional,
title = UrlParameter.Optional,
mixed = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}",
new { controller = "Article",
action = "detail"
} // Parameter defaults
);
}

Jquery Ajax Post is calling wrong action method

I will bring code first.
Controller:
public ActionResult VideoList(int page)
{
}
[HttpPost]
public ActionResult SaveWindowWidth(string width)
{
return Json(new { success = true });
}
JS:
$(document).ready(function ()
{
var width = $("#Window").width();
$.ajax(
{
type: "POST",
url: '/Video/SaveWindowWidth',
async: "true",
data: { "width": width },
dataType: 'text json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data, status)
{
if (data)
{
alert(data.status);
}
},
error: function (data, status)
{
if (data)
{
alert(data.status);
}
}
})
})
Routes:
routes.MapRoute(
"Home", // Route name
"Home", // URL with parameters
new { controller = "Home", action = "Index" }
);
routes.MapRoute(
"BookPage", // Route name
"BookPage/{page}", // URL with parameters
new { controller = "Book", action = "Page" }
);
routes.MapRoute(
"BlogMember", // Route name
"BlogMember/{id}/{page}", // URL with parameters
new { controller = "Blog", action = "Member" }
);
routes.MapRoute(
"BlogPost", // Route name
"BlogPost/{id}/{page}", // URL with parameters
new { controller = "Blog", action = "Post" }
);
routes.MapRoute(
"BlogPage", // Route name
"BlogPage/{page}", // URL with parameters
new { controller = "Blog", action = "Page" }
);
routes.MapRoute(
"BlogTag", // Route name
"BlogTag/{tag}/{page}", // URL with parameters
new { controller = "Blog", action = "Tag" }
);
routes.MapRoute(
"NewBlogPostComment", // Route name
"NewBlogPostComment", // URL with parameters
new { controller = "Blog", action = "NewBlogPostComment" }
);
routes.MapRoute(
"NewBlogPost", // Route name
"NewBlogPost", // URL with parameters
new { controller = "Blog", action = "NewBlogPost" }
);
routes.MapRoute(
"EditBlogPost", // Route name
"EditBlogPost/{id}", // URL with parameters
new { controller = "Blog", action = "EditBlogPost" }
);
routes.MapRoute(
"Account", // Route name
"Account", // URL with parameters
new { controller = "Account", action = "Update" }
);
routes.MapRoute(
"LogOff", // Route name
"LogOff", // URL with parameters
new { controller = "Account", action = "LogOff" }
);
routes.MapRoute(
"LogOn", // Route name
"LogOn", // URL with parameters
new { controller = "Account", action = "LogOn" }
);
routes.MapRoute(
"Register", // Route name
"Register", // URL with parameters
new { controller = "Account", action = "Register" }
);
//routes.MapRoute(
// "About", // Route name
// "About", // URL with parameters
// new { controller = "Home", action = "About" }
//);
routes.MapRoute(
"Contact", // Route name
"Contact", // URL with parameters
new { controller = "Home", action = "Contact" }
);
routes.MapRoute(
"UnderConstruction", // Route name
"UnderConstruction", // URL with parameters
new { controller = "Home", action = "UnderConstruction" }
);
routes.MapRoute(
"DisableBlogComment", // Route name
"DisableBlogComment/{id}", // URL with parameters
new { controller = "Blog", action = "DisableBlogComment" }
);
routes.MapRoute(
"DisableAllMemberBlogComments", // Route name
"DisableAllMemberBlogComments/{id}", // URL with parameters
new { controller = "Blog", action = "DisableAllMemberBlogComments" }
);
routes.MapRoute(
"DisableVideoComment", // Route name
"DisableVideoComment/{id}", // URL with parameters
new { controller = "Video", action = "DisableVideoComment" }
);
routes.MapRoute(
"DisableAllMemberVideoComments", // Route name
"DisableAllMemberVideoComments/{id}", // URL with parameters
new { controller = "Video", action = "DisableAllMemberVideoComments" }
);
routes.MapRoute(
"DisableMember", // Route name
"DisableMember/{id}", // URL with parameters
new { controller = "Member", action = "DisableMember" }
);
routes.MapRoute(
"NewPost", // Route name
"NewPost", // URL with parameters
new { controller = "Blog", action = "NewPost" }
);
routes.MapRoute(
"InactiveBlogPosts", // Route name
"InactiveBlogPosts/{page}", // URL with parameters
new { controller = "Blog", action = "InactiveBlogPosts" }
);
routes.MapRoute(
"InactiveBlogComments", // Route name
"InactiveBlogComments/{page}", // URL with parameters
new { controller = "Blog", action = "InactiveBlogComments" }
);
routes.MapRoute(
"InactiveVideoComments", // Route name
"InactiveVideoComments/{page}", // URL with parameters
new { controller = "Video", action = "InactiveVideoComments" }
);
routes.MapRoute(
"EditHomePage", // Route name
"EditHomePage", // URL with parameters
new { controller = "Home", action = "EditHomePage" }
);
routes.MapRoute(
"EditAboutPage", // Route name
"EditAboutPage", // URL with parameters
new { controller = "Home", action = "EditAboutPage" }
);
routes.MapRoute(
"Newsletter", // Route name
"Newsletter", // URL with parameters
new { controller = "Newsletter", action = "Newsletter" }
);
routes.MapRoute(
"RegisterNewVideo", // Route name
"RegisterNewVideo", // URL with parameters
new { controller = "Video", action = "RegisterNewVideo" }
);
routes.MapRoute(
"Members", // Route name
"Members/{page}", // URL with parameters
new { controller = "Member", action = "MemberList" }
);
routes.MapRoute(
"EditMember", // Route name
"EditMember/{id}", // URL with parameters
new { controller = "Member", action = "EditMember" }
);
routes.MapRoute(
"AppSettings", // Route name
"AppSettings", // URL with parameters
new { controller = "Utility", action = "AppSettings" }
);
routes.MapRoute(
"AudioBookPage", // Route name
"AudioBookPage/{page}", // URL with parameters
new { controller = "Book", action = "AudioBookPage" }
);
routes.MapRoute(
"IPBlocked", // Route name
"IPBlocked", // URL with parameters
new { controller = "Utility", action = "IPBlocked" }
);
routes.MapRoute(
"LiveTV", // Route name
"LiveTV", // URL with parameters
new { controller = "LiveTV", action = "LiveTV" }
);
routes.MapRoute(
"VideoPlayer", // Route name
"VideoPlayer/{id}/{page}", // URL with parameters
new { controller = "Video", action = "VideoPlayer" }
);
routes.MapRoute(
"Video", // Route name
"Video/{page}", // URL with parameters
new { controller = "Video", action = "VideoList" }
);
routes.MapRoute(
"NewVideoComment", // Route name
"NewVideoComment", // URL with parameters
new { controller = "Video", action = "NewVideoComment" }
);
routes.MapRoute(
"Music", // Route name
"Music", // URL with parameters
new { controller = "Music", action = "Index" }
);
routes.MapRoute(
"RootsCompilationOne", // Route name
"Music/RootsCompilationOne", // URL with parameters
new { controller = "Music", action = "RootsCompilationOne" }
);
routes.MapRoute(
"UnityIsStrength", // Route name
"Music/UnityIsStrength", // URL with parameters
new { controller = "Music", action = "UnityIsStrength" }
);
routes.MapRoute(
"FileUpload", // Route name
"FileUpload", // URL with parameters
new { controller = "Utility", action = "FileUpload" }
);
routes.MapRoute(
"PageUnavailable", // Route name
"PageUnavailable", // URL with parameters
new { controller = "Utility", action = "PageUnavailable" }
);
routes.MapRoute(
"VideoGrid", // Route name
"VideoGrid/{page}", // URL with parameters
new { controller = "Video", action = "VideoGrid" }
);
routes.MapRoute(
"EditVideo", // Route name
"EditVideo/{id}", // URL with parameters
new { controller = "Video", action = "EditVideo" }
);
routes.MapRoute(
"CopyVideo", // Route name
"CopyVideo/{id}/{page}", // URL with parameters
new { controller = "Video", action = "CopyVideo" }
);
routes.MapRoute(
"DeleteIPLogs", // Route name
"DeleteIPLogs/{ip}", // URL with parameters
new { controller = "Utility", action = "DeleteIPLogs" }
);
routes.MapRoute(
"SaveWindowWidth", // Route name
"SaveWindowWidth/{width}", // URL with parameters
new { controller = "Video", action = "SaveWindowWidth" }
);
routes.MapRoute(
"FacebookLikes", // Route name
"FacebookLikes", // URL with parameters
new { controller = "Utility", action = "FacebookLikes" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Problem that ajax tries to call VideoList method. I see it when read response:
The parameters dictionary contains a null entry for parameter 'page' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult VideoList(Int32)'
I have heard somewhere that it may be something wrong with routes, so I posted them here as well.
I would appreciate your help
Regards
Mariusz
Your video route is not well configured. MVC tries to get the controller and action from each url to figure out required method from appropriate controller. And in your case, it always gets same values VideoController.VideoList():
routes.MapRoute(
"Video", // Route name
"Video/{page}", // URL with parameters
new { controller = "Video", action = "VideoList" }
);
If you change your route to this, everything will be ok:
routes.MapRoute(
"Video", // Route name
"Video/{action}", // URL with parameters
new { controller = "Video", action = "VideoList" }
);
Dima has identified the issue, though his solution wouldn't quite work for you. Your routes are configured such that when requesting a url Video/SaveWindowWidth, call the action VideoList on the controller Video with the parameter page set to SaveWindowWidth. Clearly that is not what you wanted.
ASP.Net MVC will execute the first route that matches. Which is why it's important to include all specific routes first.
One of the ways to fix this is to re-write your routes such that certain API routes are configured above your generic pretty routes. To do so, you would need to mention every single combination before any pretty url.
For example,
routes.MapRoute(
"SaveWindowWidthForVideo", // Route name
"Video/SaveWindowWidth",
new { controller = "Video", action = "SaveWindowWidth" }
);
routes.MapRoute(
"SaveWindowHeightForVideo", // Route name
"Video/SaveWindowHeight",
new { controller = "Video", action = "SaveWindowHeight" }
);
routes.MapRoute(
"SaveWindowSomethingElseForVideo", // Route name
"Video/SaveWindowHeight",
new { controller = "Video", action = "SaveWindowSomethingElseForVideo" }
);
// etc etc
// your remaining pretty urls
routes.MapRoute(
"Video", // Route name
"Video/{page}", // URL with parameters
new { controller = "Video", action = "VideoList" }
);
I don't prefer to do that, as it can get rather cumbersome very easily.
The solution I prefer is to distinguish between my pretty url routes and my ajax API routes by adding the word api in the url.
routes.MapRoute(
"ApiCallsForVideo", // Route name
"api/video/{action}",
new { controller = "Video" }
);
// or
routes.MapRoute(
"ApiCalls", // Route name
"api/{controller}/{action}"
);
// etc etc
routes.MapRoute(
"Video", // Route name
"Video/{page}", // URL with parameters
new { controller = "Video", action = "VideoList" }
);
This obviously involves modifying your ajax calls to include the word api.
Use string to store value as URL is not a best practice.
I do something like this.
View
#Html.Hidden("getVideoUrl", Url.Action("SaveWindowWidth", "Video"))
JS
var url = $("#getVideoUrl").val();
$.post(url, data: { "width": width },
success: function (data, status)
{
if (data)
{
alert(data.status);
}
},
error: function (data, status)
{
if (data)
{
alert(data.status);
}
});
Hi i think you need to add parameter in route then only your ajax will call that method with parameter. Now whats happening is ur ajax is calling that particular methot but you 've not mentioned in route that to allow parameter
routes.MapRoute(
"Video", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Video", action = "VideoList", width= UrlParameter.Optional } // Parameter defaults
);
then only ur parameter can be passed to ur controller.
and calling url will look like this
url: '/Video/SaveWindowWidth'+width,
or
url: '/Video/SaveWindowWidth?width=' + width,
its working fine for me!
Hope it helps

Hiding action in url (mvc 4 web application)

I have a module called News as Area. In NewsAreaRegistration I have
context.MapRoute(
"NewsShow",
"News/{controller}/{friendlyUrlName}/{idNews}",
new { controller = "Show", action = "Index", friendlyUrlName = "", idNews = "" }
);
In my view (in main View folder) I use RouteUrl method to enforce my custom route
#Url.RouteUrl("NewsShow", new { controller = "Show", action = "Index", friendlyUrlName = FriendlyURL.URLFriendly(true, Model.News.Data.ElementAt(0).Title), idNews = Model.News.Data.ElementAt(0).IdNews})"
What I would like to do is have a route like this www.something.com/News/Show/bla-bla-bla/9
without action name Index that I have in Show controller. I tried literaly all permutations of this example and nothing worked. Is this even possible?
Ok, so I tried this out....
Routing table: (before default)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Hidden",
url: "News/{controller}/{friendlyUrlName}/{idNews}",
defaults: new {controller = "Home", action = "Index", friendlyUrlName = "", idNews = ""});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);
In the View:
#Url.RouteUrl("Hidden", new { friendlyUrlName = "Dude-Check-It-Out", idNews = 12 })
in my controller:
public ActionResult Index(string friendlyUrlName, int idNews)
{
ViewBag.Message = "Modify this template to kick-start your ASP.NET MVC application.";
ViewBag.UrlName = friendlyUrlName;
ViewBag.NewsId = idNews;
return View();
}
and I got this..
/News/Home/Dude-Check-It-Out/12
URL I go to:
http://localhost:49840/News/Home/Dude-Check-It-Out/12
I also changed my default route to something else to ensure that this wasn't using the default route. Let me know if this helped :)
Did you put this route before default one? Route position is important, from top to bottom.
Ok...I managed to work somehow.
In my NewsAreaRegistration I had to move NewsShow route before default. Not sure why, becuase RouteUrl should map excatly to NewsShow.
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"NewsShow",
"News/{controller}/{friendlyUrlName}/{idNews}",
new { controller = "Show", action = "Index", friendlyUrlName = "", idNews = "" }
);
context.MapRoute(
"News_default",
"News/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
This is my RouteUrl now (notice I had to write controller.Not sure exactly why either:
#Url.RouteUrl(
"NewsShow", new { controller = "Show", friendlyUrlName = FriendlyURL.URLFriendly(true, Model.News.Data.ElementAt(0).Title), idNews = Model.News.Data.ElementAt(0).IdNews }
);

How can i set route for action with string parameter for username and password?

i have action in controller with this code:
[Authorize(Roles = "members")]
[HttpPost]
public ActionResult login(string uname,string pass)
{
MembersSrv mm = new MembersSrv();
if (mm.validateUsers(uname,pass)==true)
{
mm.CreateCookie(uname, pass);
return RedirectToAction("Index");
}
else
return RedirectToAction("Login");
}
how can i get this url?
http://localhost:5555/Members/Login
is this route true?
routes.MapRoute(
"Login", // Route name
"Members/{action}/{Uname}", // URL with parameters
new { action = "Login", Uname =" " } // Parameter defaults
);
You need a GET action for that
public ActionResult Login()
{
return View();
}
[Authorize(Roles = "members")]  
[HttpPost]
public ActionResult login(string uname,string pass)
{
//your code handle login when form posted
}
This can be accessed like
http://yourdomainname/members/login
Assuming login action belongs to membersController.
When user posts the form, your HttpPost action method will handle that.
You may not need those routes you defined. you will be fine with the default routes you have.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The route of Members Area is :
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Members_default",
"Members/{controller}/{action}/{id}",
new { action = "Login", id = UrlParameter.Optional }
);
}
can I change it to:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Members_default",
"Members/{action}/{id}",
new { action = "Login", id = UrlParameter.Optional }
);
}

The urlHelper.RouteUrl is not producing Correct URL

When the links are generated Code is in the Indexx of the controller.
So the Link Are Generated in this form
Wk/Index/XX/YYYY
The url Code is
url = urlHelper.RouteUrl("Wk", new { slug});
But i need the link will Be in This form
Wk/C/XXX
Here c is the other Action name
How can this be achieved.
My Global Asax Looks like
routes.MapRoute(
"Default", // Route name
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "Index" , id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Wk", // Route name
"{controller}/{action}/{slug}/{id}", // URL with parameters
new { controller = "Wk", action = "c", slug = "", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Book", // Route name
"{controller}/{id}/{pageNo}", // URL with parameters
new { controller = "Book", action = "Index",id = UrlParameter.Optional,pageNo = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"UserArea", // Route name
"{controller}/{slug}/{id}", // URL with parameters
new { controller = "UserArea", action = "Index", slug = UrlParameter.Optional, id = UrlParameter.Optional } // Parameter defaults
);
Try like this:
var url = urlHelper.RouteUrl("Wk", new { action = "C", slug = "XXX" });

Resources