What difference between using IController in mvc 4 and mvc 5? - asp.net

I tried write code what is working in MVC 4 using VS2012.
RouteConfig.cs
namespace MvcApplication2012
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "SayHello",
url: "hello",
defaults: new { controller = "hello" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
IController.cs
namespace MvcApplication2012.Controllers
{
public class HelloController : IController
{
public void Execute(System.Web.Routing.RequestContext requestContext)
{
requestContext.HttpContext.Response.Write("Hello, world!");
}
}
}
This code works fine in MVC 4 using VS2012, but not work in MVC 5 using VS2015.
What is defference? Why it not work?
Returns error
enter image description here

Bassically I found answer, I forgot set class HelloController as public:( But now all is works

Related

Why A simple method having two arguments is not working in ASP.NET MVC?

My controller:
public class AjaxController : Controller
{
private readonly IGenerationUnitMobileService _generationUnitMobileService;
public AjaxController(IGenerationUnitMobileService generationUnitMobileService)
{
_generationUnitMobileService = generationUnitMobileService;
}
public IActionResult MobileExistToAnotherGenerationUnit(String mobile, long generation_unit_id)
{
//ViewBag.Result = _generationUnitMobileService.MobileExistToAnotherGenerationUnit(mobile,generationUnitId);
return View();
}
}
And My view file is very simple:
#model PgcgSms.WebSite.Models.GenerationUnitMobileViewModel
#{
Layout = "~/Views/Shared/_Ajax.cshtml";
}
#ViewBag.Result
This is so much straight forward. But when I browse at: http://localhost:57216/Ajax/MobileExistToAnotherGenerationUnit/01719393045/1
I am getting the following error message:
This localhost page can’t be found
No webpage was found for the web address: http://localhost:57216/Ajax/MobileExistToAnotherGenerationUnit/01719393045/1
Search Google for localhost 57216 Ajax Mobile Exist To Another Generation Unit 01719393045
HTTP ERROR 404
I checked the view file and spellings several times. Whats wrong with my code?
In the RouteConfig.cs file you will have to specify the default route.
For Example:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "AjaxController", action = "MobileExistToAnotherGenerationUnit", id = UrlParameter.Optional }
);
}
}

Default attributing routing not working

I am working on a new project and i have decided to use attribute routing alone. This is my RouteConfig file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}",
// defaults: new { controller = "HomeController", action = "Index", id = UrlParameter.Optional }
//);
}
This is my controller:
[RoutePrefix("home")]
public class HomeController : Controller
{
[Route]
[Route("~/")]
public ActionResult Index()
{
var status = HttpContext.User.Identity.IsAuthenticated;
ViewBag.Title = "Home Page";
return View();
}
[Route("test")]
public ActionResult Test()
{
return View();
}
}
I've realised that typically all my attributes are working but i want the Index method to run on application start. Say https://example.com and then the Index method is fired as if i entered the url https://example.com/home/index. I get a blank space when i do say https://example.com.
Can anyone please help me understand why i get a blank space and also how to set the default application start route using attribute routing? I've been surfing the internet for hours but i can't lay my hands on anything.
In your case you should still set a default route. That way the site knows where to start. From there everything else should work as you intended.
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{action}",
defaults: new { controller = "Home", action = "Index" }
);
}
Here is my Home Controller.
public class HomeController : FrontOfficeControllerBase {
public HomeController() {
}
public ActionResult Index() {
...
return View();
}
}
Other than that this keeps my route config clean as I use attribute routing everywhere else.
Try this:
[RoutePrefix("home")]
public class HomeController : Controller
{
[Route("index")]
[Route("~/", Name = "default")]
public ActionResult Index()
{
...
}
...
}

Alternative to MapPageRoute using the MVC pattern

I want access to some pages of my website with "web.com/software" or "web.com/about", but I'm using the MVC pattern and the MapPageRoute method (inside RouteConfig.cs) only works with pages without controllers.
If Home is my controller and Software the view, I want access with "web.com/software" instead of "web.com/Home/Software".
Is it possible with ASP.NET or I need use rewrites in Web.config (IIS) and .htaccess (Apache)?
namespace MyWebsite
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("SoftwarePage",
"software", // web.com/software
"~/Views/Home/Software");
//routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}

Why isn't my ASP.NET API route being called, is my URL not correct?

I have a new ASP.NET MVC 5 application.
I added an /api folder in my controllers folder and added a MVC2 API controller.
My global.asax has:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
My controller looks like:
public class UsersController : ApiController
{
[HttpGet]
[ActionName("User")]
public IToken GetUser()
{
return new User();
}
}
Now I get a 404 resource cannot be found error when I go to:
http://localhost:53323/api/users/user
http://localhost:53323/api/users/getuser
What could the problem be?
Update
My MVC route config:
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 }
);
}
My API route config:
config.MapHttpAttributeRoutes();
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Seems like you are missing correct registration in your Application_Start().
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration); // This should be above the default route registration.
RouteConfig.RegisterRoutes(RouteTable.Routes);
//GlobalConfiguration.Configure(WebApiConfig.Register); // Remove this line.
}
Try using attribute routing on your controller and action methods.
Example
[RoutePrefix("api/users")]
public class UsersController : ApiController
{
[HttpGet]
[Route("user")]
public IToken GetUser()
{
return new User();
}
}

MVC 4 Web API Areas 404 Error: "The controller for path '/Jobs/Send' was not found or does not implement IController."

I'm having an issue that is driving me nuts.
I have an MVC 4 WebAPI application that has several Areas defined.
My Jobs Area Send controller (SendController.cs) is defined like so:
namespace TargetAPI.Areas.Jobs.Controllers
{
public class SendController : ApiController
{
[HttpPost]
public HttpResponseMessage Index(SendRequest req)
{
try
{
//blah blah
}
catch (Exception ex)
{
//blah blah
}
}
}
}
My Jobs Area Registration (JobsAreaRegistration.cs) is defined like so:
namespace TargetAPI.Areas.Jobs
{
public class JobsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Jobs";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Jobs_long",
"Jobs/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "TargetAPI.Areas.Jobs.Controllers" }
);
}
}
}
My RouteConfig.cs says:
namespace TargetAPI
{
public class RouteConfig
{
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 },
namespaces: new string[] { "TargetAPI.Controllers" }
);
}
}
}
When I run the route debugger on it I get:
(source: boomerang.com)
But when I try to post to the URL "Jobs/Send" I get:
The controller for path '/Jobs/Send' was not found or does not implement IController.
I've tried so many iterations and combinations my head is spinning. Any ideas?
Thanks!
Turns out the WebAPI does NOT handles Areas! Imagine my surprise. So I found a GREAT post http://blogs.infosupport.com/asp-net-mvc-4-rc-getting-webapi-and-areas-to-play-nicely/. Now I am moving forward.
In addition to not supporting Areas (because MapHTTPRoute doesn't have namespace support), The API controller must use MapHttpRoute, not MapRoute as in this example (after removing area):
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Note the absence of {action}, the Method's are not Actions, put are taken from the HTTP request: Get, Head, etc...
I had the same problem, the solution was simple: I forgot to add files _ViewStart.cshtml and _Layout.cshtml, and can help you

Resources