Angularjs cant find view, tried everything I know - asp.net

I have made a project using ng.Net template from visual studio, i got it up and running, i added a new ProgramController.cs, Program.cshtml template, programCtrl.js angular controller, and a program angular module.
And it just will not work.
I have a ASP.NET web api and angularjs on clientside.
Here are 2 example routes:
$routeProvider.when('/todomanager', {
templateUrl: 'App/TodoManager',
controller: 'todoManagerCtrl'
});
$routeProvider.when('/program', {
templateUrl: 'App/Program',
controller: 'programCtrl'
});
And what they do backend:
[HttpGet]
[Authorize]
public List<Program> GetPrograms()
{
string userId = Request.GetOwinContext().Authentication.User.Identity.GetUserId();
var currentUser = UserManager.FindById(userId);
return currentUser.Programs;
//return db.Programs;
}
[HttpGet]
[Authorize]
public List<todoItem> GetUserTodoItems()
{
string userId = Request.GetOwinContext().Authentication.User.Identity.GetUserId();
var currentUser = UserManager.FindById(userId);
return currentUser.todoItems;
}
The first one works, the second one gives tpload compile error (could not find template view)
I can get the TodoManager view if I call it in /program
But I cant reach my program.cshtml. It's in the same folder as TodoManager.cshtml
I could provide more code, But I dont know which, Because it all works.
My closest guess so far, is that I dont have access to that view, I'm being blocked by a blockviewhandler or the view doesnt exist.
I have the access.
If it was the viewblockhandler it would also block TodoManager.cshtml
And it exists xD I'm looking at it..
It's like i'm spamming 4 + 4 on a calculator and it keeps returning 5..
Please, anything, been stuck for 2 workdays.
EDIT additional code
//RouteConfig RegisterRoutes
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "App",
url: "{url}",
defaults: new { controller = "Main", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Main", action = "Index", id = UrlParameter.Optional }
);
}
//WebApiConfig Register
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
//I chaned the routeTemplate so that methods/services would be identified by their action, and not by their parameters.
//I was getting conflicts if I had more than one GET services, that had identical parameter options, but totally different return data.
//Adding the action to the routeTemplte correct this issue.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}", //routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
//blockviewhandler in Web.config
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*." verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
Edit: Project structure, i have a HomeController that returns my Index.cshtml in there, i have my ng-view which is where my views should be rendered.
Many seem to misunderstand my real question, i want to know:
How is it, that the todoManager works, and the program does not.

When using ASP.NET MVC, Web API etc. you should add "every" view to the mvc controller, you probably have something like this in one of your controllers:
public ActionResult TodoManager()
{
return PartialView();
}
assuming you are following a tutorial or modifying a sample it is probably in Controllers/AppController. If true you must add your another view as:
public ActionResult Program()
{
return PartialView();
}

Related

Http route without parameters and a point inside the route

I'm currently creating a webservice using ApiController classes. Due to some restrictions I have to put a Point in the route itself (terminal.journalentry). And use this as the base URL. Thus:
http://localhost:59684/terminal.journalentry
as example for a call. Now though I've run into Problems.
When I use the following code with this call: http://localhost:59684/terminal.journalentry it works without a hitch.
public class JournalController : ApiController
{
[HttpGet]
[Route("terminal.journalentry/{id}")]
public void WriteJournalEntry(int id)
{
}
}
Though I Need to use the method without any Parameters involved. But when I try the following:
public class JournalController : ApiController
{
[HttpGet]
[Route("terminal.journalentry")]
public void WriteJournalEntry()
{
}
}
With the call being: http://localhost:59684/terminal.journalentry
I get:
HTTP Error 404.0 - Not Found
Now my question is: What is wrong there and what Needs to be done in order to use the above URL without running into Errors?
Edit as it was asked what the Content of Routes.config is:
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 }
);
}
}
WebApiConfig.cs has only the following Content inside Register: config.MapHttpAttributeRoutes();
I think you need to configure a handler to ignore the ".journalentry".
Usually anything with a fullstop is considered a file, and I imagine this is happening here.
In the web.config for your API, try and find the following section:
<system.webServer>
<handlers>
And add a handler definition:
<add name="JournalEntryExtensionHandler" path="*.journalentry*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
You might need to play around a bit with the path wildcard settings.
When I've done this previously the URL ended with a filename so the path was "*.jpg" for example.

Trying to display Custom View in MVC app but it says requested URL not found

I am new to azure, MVC and also ASP.NET. I am writing MVC Cloud service with ASP.NET web role. Please help me with this problem
When I create the application there are default views but I wanted to see my view so I set my view as start page. I also changed the values in RegisterRoutes method
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "User", action = "AddUser", id = UrlParameter.Optional }
);
}
When I run the app, it gives HTTP 404 error because it could not find request URL : /Views/User/AddUser.cshtml
In MVC you don't put the view in the URL to get it rendered.
This won't work: /Views/User/AddUser.cshtml
As you've correctly put in your question the default route is {controller}/{action}/{id} with id being optional.
So assuming that User is your controller, i.e. you have a class called UserController, which looks something like:
namespace My.Controllers
{
public class UserController : Controller
{
which has an action on it called AddUser:
public ActionResult AddUser()
{
// implementation logic
return View();
}
Then the default route will display your view when it processes the URL /User/AddUser
In MVC 5, this looks something like:

asp.net WEB API: Routing - Action before Controller. Possible workaround?

I am developping a WEB API using asp.net and my goal is to be able to call this type of url's:
/html/countries/...
/json/countries/...
Countries is a controller, and depending on the parameter before it returns different result.
What i did and it doesn't seems to work:
routes.MapRoute(
name: "Default",
url: "api/{action}/{controller}",
defaults: new
{
}
);
CountriesController:
[ActionName("html")]
public string get()
{
//...
}
[ActionName("json")]
public void getType()
{
//...
}
Any sugestions?
EDIT:
I have like 7 controllers.
And there are some possible urls:
/html/{controller}/x/y
/json/{controller}/x/y/order/h
/html/{controller}/x/z/order/y/j
/json/{controller}/x/z/order/y/j
Allow me by start saying that if "html" or json action means "format" those should not be part of your controller they are media types and needs to be configured differently
Web Api v1 defines resources globally in the global.asax on application_start event. Assuming you are using Visual Studio 2013 and based Microsoft default template your method may look like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
WebApi routing configuration occurs here WebApiConfig.Register while your MVC configuration occurs here RouteConfig.RegisterRoutes
Your WebApi routing configuration should look like this
public static class WebApiConfig{
public static void Register(HttpConfiguration config){
config.Routes.MapHttpRoute(
name: "htmltApi",
routeTemplate: "html/{action}/{controller}",
);
config.Routes.MapHttpRoute(
name: "jsonApi",
routeTemplate: "json/{action}/{controller}",
);
...
Another important detail is that WebApi v2 introduced something called Route Attributes those can be used along with your Controller class and can facilitate the routing configuration.
For example:
public class BookController : ApiController{
//where author is a letter(a-Z) with a minimum of 5 character and 10 max.
[Route("html/{id}/{newAuthor:alpha:length(5,10)}")]
public Book Get(int id, string newAuthor){
return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
}
[Route("json/{id}/{newAuthor:alpha:length(5,10)}/{title}")]
public Book Get(int id, string newAuthor, string title){
return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
}
...
Thanks to the Dalorzo answer i did find the problem:
The problem occurred because my application was created the following way:
which resulted in creation of both files, RouteConfig.cs (MVC) and WebApiConfig.cs (WEB API):
What is WRONG is that the code in the question is from RouteConfig.cs
After putting the code
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{action}/{controller}",
defaults: new
{
action = "html"
}
);
in WebApiConfig.cs, it worked proper way.

Why is the ASP.NET routing engine ignoring files?

I have a class that implements both IHttpHandler and IRouteHandler:
public class CustomHandler : IHttpHandler,IRouteHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("Content-Type", "text/plain");
context.Response.Write("Hello World");
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return this;
}
}
In the Application_Start method I try to register my handler with route:
Route route = new Route("dav/{*Pathinfo}", new CustomHandler());
RouteTable.Routes.Add(route);
Everything is cool until I call with this kind Url:
- http://localhost:63428/dav/asdadsa
- http://localhost:63428/dav/asdadsa/asdasd
- http://localhost:63428/dav/asdadsa/a%20%20sdasd (with space in the url)
But if I try with theese:
- http://localhost:63428/dav/asdadsa.docx
- http://localhost:63428/dav/asdads/a.docx
My handler not called and the server return with 404. I thought that the wildcard will match every url which start with dav/.
Any idea how to achive that the urls with extensions also match to my route?
UPDATE:
I found this page.
It's set from config, not from code behind but don't have to set the runAllManagedModulesForAllRequests settings and unfortunately don't get the route values so clean that in my original example.
Maybe somebody will be intrested if come to this question for answers.
If you add the following configuration to your web.config file then your routing will include files as well.
<configuration>
<system.webServer>
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
<!-- more -->
</modules>
</system.webServer>
</configuration>
One different solution is to add <modules runAllManagedModulesForAllRequests="true"> but that gives an overhead in that all your registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.
You can read more here about the different routing settings.
Just remember, if you're adding your special routing to the existing routing you have to add your routing first or it won't be processed, as in this example.
Route route = new Route("dav/{*Pathinfo}", new CustomHandler());
routes.Add(route);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
One problem with this approach is that the first route definition confuses Html helpers in your system so you won't any longer get nice routes like localhost/home/index but instead localhost/dav?action=index&controller=home. The solution to this is to restrict the first route to only be valid on incoming route requests. This can be done by creating a RouteConstraint and add it to the route definition in a RouteValueDictionary.
public class OnlyIncomingRequestConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest)
return true;
return false;
}
}
You can then redefine your route definition in this way:
Route route = new Route("dav/{*Pathinfo}", new RouteValueDictionary(new { controller = new OnlyIncomingRequestConstraint() }), new CustomHandler());
routes.Add(route);
After this your default routes should be back to normal again.

Asp.net Web API: No action was found on the controller

So this has really been causing me a headache.
Route:
config.routes.MapHttpRoute(
name: 'ControllerAction' ,
routeTemplate: "api/{controller}/{action}"
);
Controller:
public class LookupsController : ApiControllerBase
{
[ActionName("all")]
public Lookups GetLookups()
{
var lookups = new Lookups
{
Customers = GetCustomers().ToList(),
//add more
};
return lookups;
}
}
but whenver I try to hit the uri: /api/lookups/all
I get a 404 error saying:
"No action was found on the controller 'Lookups' that matches the name 'all'."
Any help would be appreciated
EDIT:
So I figured it out finally.
it was because of the wrong depency.
VS2012 autoresolved the action to system.web.mvc.actionnameattribute while what I needed was system.web.http.actionnameattribute.
weird problem, anyways, I hope this helps someone else.
Jakob Li,
EDIT:
You are renaming the controller but not specifying the method. WebApi resolves the method from the prefix GET, PUT, DELETE, POST. So the method attribute must be placed at the signature of the action:
Try this, works well for me:
public class LookupsController : ApiControllerBase
{
[HttpGet()]
[ActionName("All")]
public Lookups GetLookups()
{
var lookups = new Lookups
{
Customers = GetCustomers().ToList(),
//add more
};
return lookups;
}
}
routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Take a look here for more information about routing:
Routing in ASP.NET Web API
Hopes its help you!

Resources