Resource not found error - c#

I have a problem with accessing a method on my HomeController. I show you the code of the method :
[HttpGet]
public ActionResult DecriptIdentifiantEtRedirige(string login_crypter, string mdp_crypter)
{
string loginAcrypter = _globalManager.ProtegeMotDePasse(login_crypter);
string MdpAcrypter = _globalManager.ProtegeMotDePasse(mdp_crypter);
User UserApp = new Models.User(login_crypter, mdp_crypter);
if (UserApp.AuthentificationValidee(UserApp.UserLogin, UserApp.Password))
{
Session["Name"] = UserApp.UserLogin;
return RedirectToAction("Accueil", "Home");
}
else
{
return RedirectToAction("ValiderAuthentification", "Home");
}
}
Then in the RouteConfig.cs i wrote the route like that :
routes.MapRoute(
name: "AuthentificationApresDecryptage",
url: "{controller}/{action}/{login_crypter}/{mdp_crypter}",
defaults: new { controller = "Home", action = "DecriptIdentifiantEtRedirige", login_crypter = "", mdp_crypter = "" }
);
But the problem is that when i try to access that method in the browser with that link:
"http://mydomain.com/DecriptIdentifiantEtRedirige/12345/54321"
It shows me an error : "Resource not found".
Somebody has an idea ?
Thanks.

Try this,
routes.MapRoute(
name: "AuthentificationApresDecryptage",
url: "{controller}/{action}/{login_crypter}/{mdp_crypter}",
defaults: new { controller = "Home", action = "DecriptIdentifiantEtRedirige", login_crypter = UrlParameter.Optional, mdp_crypter = UrlParameter.Optional }
);

Related

MVC querystring parameter not passing through to action

I have the following action:
public ActionResult CatchAll(string pathname, bool isPreview)
{
CatchAllModel model = _aliasModelBuilder.BuildCatchAllModel(pathname, isPreview);
if (model.Page != null)
{
return View(model);
}
else
{
throw new HttpException(404, "Page not found");
}
}
And the route for this is
routes.MapRoute(
name: "Default",
url: "{*pathname}",
defaults: new { controller = "Alias", action = "CatchAll", isPreview = false });
Now if I browse to localhost/about-us?isPreview=true, the pathname comes through as about-us but isPreview comes through as false.
Is there anything I'm doing wrong - I thought the route default should be overwritten by the query string
Ok this looks as if the default parameter set in the route is not being overwritten by the querystring. So I removed it from the route:
routes.MapRoute(
name: "Default",
url: "{*pathname}",
defaults: new { controller = "Alias", action = "CatchAll" });
And added it to the action:
public ActionResult CatchAll(string pathname, bool isPreview = false)
I guess I'll have to suppress CA1026 as we can't make overload methods for actions

C# Mvc Generic Route using Slug

I'm trying to create a generic route to work with slugs, but I always got an error
The idea is, instead of www.site.com/controller/action I get in the url a friendly www.site.com/{slug}
e.g. www.site.com/Home/Open would be instead www.site.com/open-your-company
Error
server error in '/' application The Resource cannot be found
In my Global.asax I have
public static void RegisterRoutes(RouteCollection routes)
{
//routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("DefaultSlug", "{slug}", new { controller = "Home", action = "Open", slug = "" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
area = "",
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
slug = ""
}
);
}
In one of my cshtml I have the following link (even when it's commented, there is still the same error).
#Html.ActionLink("Open your company", "DefaultSlug", new { controller = "Home", action = "Open", slug = "open-your-company" })
EDIT: HomeController
public ActionResult Open() {
return View(new HomeModel());
}
In Global.asax you slug can not be empty,if empty ,the url will be not go to the default route
public static void RegisterRoutes(RouteCollection routes)
{
//routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultSlug",
url: "{slug}",
defaults: new { controller = "Home", action = "Open" },
constraints: new{ slug=".+"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
area = "",
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}
And update the HomeController
public ActionResult Open(string slug) {
HomeModel model = contentRepository.GetBySlug(slug);
return View(model);
}
Testing Route link...
#Html.RouteLink("Open your company", routeName: "DefaultSlug", routeValues: new { controller = "Home", action = "Open", slug = "open-your-company" })
and Action link...
#Html.ActionLink("Open your company", "Open", routeValues: new { controller = "Home", action = "Open", slug = "open-your-company" })
both produces...
http://localhost:35979/open-your-company
Here's the steps I took to accomplish a similar task. This relies on a custom Slug field on the model to match against the route.
Set up your controller e.g. Controllers\PagesController.cs:
public class PagesController : Controller
{
// Regular ID-based routing
[Route("pages/{id}")]
public ActionResult Detail(int? id)
{
if(id == null)
{
return new HttpNotFoundResult();
}
var model = myContext.Pages.Single(x => x.Id == id);
if(model == null)
{
return new HttpNotFoundResult();
}
ViewBag.Title = model.Title;
return View(model);
}
// Slug-based routing - reuse View from above controller.
public ActionResult DetailSlug (string slug)
{
var model = MyDbContext.Pages.SingleOrDefault(x => x.Slug == slug);
if(model == null)
{
return new HttpNotFoundResult();
}
ViewBag.Title = model.Title;
return View("Detail", model);
}
}
Set up routing in App_Start\RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
// Existing route register code
// Custom route - top priority
routes.MapRoute(
name: "PageSlug",
url: "{slug}",
defaults: new { controller = "Pages", action = "DetailSlug" },
constraints: new {
slug = ".+", // Passthru for no slug (goes to home page)
slugMatch = new PageSlugMatch() // Custom constraint
}
);
}
// Default MVC route setup & other custom routes
}
}
Custom IRouteConstraint implementation e.g. Utils\RouteConstraints.cs
public class PageSlugMatch : IRouteConstraint
{
private readonly MyDbContext MyDbContext = new MyDbContext();
public bool Match(
HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection
)
{
var routeSlug = values.ContainsKey("slug") ? (string)values["slug"] : "";
bool slugMatch = false;
if (!string.IsNullOrEmpty(routeSlug))
{
slugMatch = MyDbContext.Pages.Where(x => x.Slug == routeSlug).Any();
}
return slugMatch;
}
}

ASP.NET MVC Routing 404 error

First I want to show code
routes.MapRoute(
name: "SubCategory",
url: "Category/{categoryName}/{subName}",
defaults: new { controller = "Categories", action = "SubCategory", categoryName = "", subName = "" }
);
this is my route
categoryName and subName are variables
// GET: Category/{categoryName}/{subName}
public ActionResult SubCategory(string categoryName, string subName)
{
CategoriesViewResult viewResult = new CategoriesViewResult();
viewResult.Categories = _db.Categories.ToList();
viewResult.CurrentSubCategory = _db.SubCategories.First(x => x.Category.CategoryName == categoryName && x.SubCategoryName == subName);
return View(viewResult);
}
this is my method;
but I get 404.
how should i write my routes.
UPDATE
this is above default route.
Try it like this
routes.MapRoute(
"SubCategory",
"Category/Sub/{categoryName}/{subName}",
new { controller = "Categories", action = "SubCategory", apiId = UrlParameter.Optional }
);
Also, which version of MVC are you using?

ASP.net MVC routing

I just created below action in my controller:
public ActionResult Serial(string letterCase)
{
string serial = "SAM_ATM_1.0.0";
if (letterCase == "lower")
{
return Content(serial.ToLower());
}
return Content(serial);
}
and added below routing rules above default action:
routes.MapRoute(
name: "Serial",
url: "serial/{letterCase}",
defaults: new { controller = "Home", action = "Serial", letterCase = "upper" }
);
However calling url http://localhost:5532/home/serial/lower in debug session, letterCase is passed with null value.
Because you call localhost:5532/home/serial/lower, try to call localhost:5532/serial/lower
or, if you need localhost:5532/home/serial/lower, rewrite your route rule to
routes.MapRoute(
name: "Serial",
url: "home/serial/{letterCase}",
defaults: new { controller = "Home", action = "Serial", letterCase = "upper" }
);

Not Passing Through Application Error When Controller Doesn't Exist

I want to use Application_Error() in global.asax to log bad URL's on a website and redirect to custom error landing page. The problem is why does the website not passing through application error when controller doesn't exist.
I tested the following URL's and everything passed through application error:
http://localhost:11843/Account/randomtext
http://localhost:11843/Home/randomtext/randomval
This one doesn't pass through application error and returns 404:
http://localhost:11843/nonExistingController
Application error code:
protected void Application_Error(object sender, EventArgs e)
{
var requestTime = DateTime.Now;
Exception ex = Server.GetLastError().GetBaseException();
//log Request.Url.ToString()
}
RouteConfig.cs code:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Account",
url: "Account/{action}/{id}",
defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Home",
url: "Home/{action}/{test}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "HomeBlank",
url: "",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Please add the following to your RouteConfig.cs :
routes.MapRoute(
name: "NotFound",
url: "{*url}",
defaults: new { controller = "Error", action = "NotFound", id = UrlParameter.Optional }
);
Some URLs will fail to be parsed and adding above will handle these cases. In your action NotFound of ErrorController, you can show the user your Custom Error page.
public class ErrorController : Controller
{
public ActionResult NotFound()
{
Response.StatusCode = 404;
return View();
}
}

Categories

Resources