How to convert all urls of my Project in lowercase in angular js application? - url-routing

Is there any solution to implement a single method or setting one Place and can apply it to all Urls of my project? Like Web.config or App.config Setting or in single JS file?

Note:- Solution For MVC Application
one solution i have found for my Question Is That
set this
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Home", id = UrlParameter.Optional },
namespaces: new[] { "VSMDiamonds.Controllers" }
);
}
}

Related

Issue with routing in angular 2 app with asp.net MVC 5 application

I have an angular 2 app which is working fine except for the routing. It is running alongside an MVC5 asp.net app.
The issue is that it always goes to the default route. That is to say, that none of the routes that I provide find a match.
#RouteConfig([
{ path: '/Page1', name: 'Page1', component: Page1Component, useAsDefault: true },
{ path: '/Page2', name: 'Page2', component: DPage2Component, useAsDefault: false }
])
If I try to navigate to: "localhost:8000/Page2" then the MVC view for Page2 is loaded correctly, but then the url is changed to localhost:8000/Page2/Page1 and the angular app for Page1 will load.
I have tried using <base href="/"> in the head of the html page and I have tried with and without the / slashed in the path, but none of there seem to match.
My MVC route config is as follows:
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" }
);
});
Any ideas on this? Even some logging would be helpful.
I have tried switching from angular2 beta8 to beta 16, but this has not resolved the issue.
Try using the following in config.MapRoute
app.UseMvc(config =>
{
config.MapRoute(
name: "Default",
url: "{*.}",
defaults: new { controller = "Home", action = "Index" }
);
});

using $stateProvider with asp.net web api

I am learning angular and web api and stuck a bit with routing. For example I want to display products using the following localhost:53967/products.
My application file is as follow.
(function () {
var productListApp = angular.module("productManagement", ["common.services", "ui.router"]);
productListApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");//default url
$stateProvider.state("productList", {
url: "/products",
templateUrl: "app/products/productListView.html",
controller: "ProductListController"
})
});
})();
I also have an Index.cshtml pageset up as follow.
<div class="container">
<div ng-view></div>
</div>
WebApiConfig
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
This is my Global.asax file
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
localhost:53967/products returns a 404.
What could be the mistake?
Regards
localhost:53967/products returns a 404. What could be the mistake?
You are probably looking for http://localhost:53967/api/products instead of http://localhost:53967/products. Make sure that you are consistent with your route declarations:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
You've got an api/ prefix over there, so the client should also respect this.

AngularJS controller is not reaching webapi

In the interest of crawling before walking with angularjs, I have created a simple application to display results from a sql server table using webapi. unfortunately the webapi is never called, because the routing is wrong, but I am not sure how to resolve. fiddler shows a 404 error.
the cshtml is as follows, defining the app and controller.
<script type="text/javascript">
var app = angular.module('streamApp', []);
app.controller('streamController', function($scope, $http){
$scope.loading = true;
$scope.addMode = false;
//Used to display the data
$http.get('/api/Stream/').success(function (data) {
$scope.streams = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading streams!";
$scope.loading = false;
});
});
</script>
the rendering section in the cshtml file is
<div data-ng-app="streamApp" data-ng-controller="streamController" class="container">
....
</div>
The webapi class is in a folder named WebApi in the MVC project, but since it is never reached, there is no point in displaying its code. it is non-descript anyway.
The route config is as follows:
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 }
);
}
}
I am not sure if I need to specify route instructions in angularjs code or in mvc route config, and exactly what functions or configuration to supply. I have tried moving the webapi class to the Controllers folder with the same results - http 404. Any advice on how to make this example get to the webapi code would be appreciated.
well hot-diggity....I solved the immediate problem by adding the annotation to my webapi class method
[Route("api/stream")]
[System.Web.Http.HttpGet]
public IEnumerable<Models.StreamViewModel> Get()
{
.....
}
so now the question is should something be done with RouteConfig as a better practice? Or is the Route() annotation the preferred way to go? or is it 6 of one half a dozen of the other?
Answer to your updated question , Best Practice of routing:
Route() annotation is the preferred way of doing this.
MVC 5 supports a new type of routing, called attribute routing. As the
name implies, attribute routing uses attributes to define routes.
Attribute routing gives you more control over the URIs in your web
application.
The earlier style of routing, called convention-based routing, is
still fully supported. In fact, you can combine both techniques in the
same project.
There are other advantages of attribute routing like
It puts the route information adjacent to the controller action that
implements that route. This helps in debugging and troubleshooting,
as well as providing an ability to quickly search for route
information in your solution.
It reduces risk in the process of making changes to routes. In RouteConfig.cs or WebApiConfig.cs (in the case of Web API solutions),
the possibility exists to inadvertently change the wrong route or
otherwise adversely affect other parts of your application.
You may also want to include acceptable HTTP methods, permitted user types and registration priorities, which if included with the
attribute-based routes, put all of that information together in one
place.
This post provided inspiration and reinforcement for me on the above, and goes into more detail:
http://kevinmontrose.com/2011/07/25/why-i-love-attribute-based-routing/
You can use either, but without the annotation your endpoint would have been api/get not api/stream (assuming you didn't rename your method).
First , you should use ApiController rather then Controller, as it take a role of an api action.
Second, If we take a look, it looks like you created a controller named ApiController, and a function called Stream. Otherwise, its a misunderstanding of the designing your web integration using MVC.
App_Start\WebApiConfig.cs:
using System.Web.Http;
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
}
}
Global.asax.cs:
using System.Web.Http;
...
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
and ApiControllerNameController: //The Controller word closes the file name, and will be reached without writing it:
using System;
..
..
..
namespace MvcApplication1.Controllers
{
public class ValuesController : ApiController
{
// GET api/values/MethodName
public IEnumerable<int> MethodName()
{
return new List<int> { 1, 2, 3 };
}
}
}

Unified MVC Controller Routing in Asp.Net 5

During my working in ASP.NET 5, I am confused in some of the unified controller concepts. Please show me what I doing wrong.
In ASP.NET 5 the same controller is used for MVC and WebApi with only the difference of Routing attribute defined above a Web Api controller. My thoughts is that the "Route" attribute is only used to define a route. But there has been some occurances that defining "Route" attribute at the top is specifing a controller to be a Web Api controller.
In Startup.cs, I have the following routing configurations.
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapWebApiRoute(
"DefaultApi",
"api/{controller}/{id?}");
});
In Home Controller, there is "HttpGet" action for accepting WebApi get request, but it cannot be called without "Route" attribute, however the routing for the web api is already defined in the startup class.
public class HomeController : Controller {
public IActionResult Index() {
return View();
}
//[Route("api/[controller]")]
[HttpGet]
public IEnumerable<string> Get() {
return new string[] { "value1", "value2" };
}
}
And in Values controller, "About" action can't be accessed as the call to "/values/about" will give an error not found. And "/api/values/about" will redirected to the "Get" action.
[Route("api/[controller]")]
public class ValuesController : Controller {
public IActionResult About() {
ViewData["Message"] = "Your application description page.";
return View();
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get() {
return new string[] { "value1", "value2" };
}
}
But although I have specified the web api route in startup.cs file, I cant access the "/api/home" path.
What am I doing wrong?
I believe you are mixing different routing methods.
Because the controllers are unified, you do not have to specify a route for webapi and another one for MVC.
The MapWebApiRoute function is only for backwards compatibility with code written for the older WebApi 2 ASP.NET.
If you want to use the convention based routing, you can just leave the UseMvc empty like this:
app.UseMvc();
For a thorough explanation of the different options, please see this useful blogpost: ASP.NET 5 Deep Dive: Routing.
Also see this question about the non-existing differences between MVC and WebApi Controllers in ASP.NET 5.

How to link a model to a router's routes

I know this is a beginner question, but I read the doc, some tutorials, and I still have a hard time making it work.
I have a simple php rest webservice, you can see the declared urls:
$app->get('/todos', 'getTodos');
$app->post('/todo/add', 'addTodo');
$app->put('/todo/update/:id', 'updateTodo');
$app->delete('/todo/delete/:id','deleteTodo');
Here is my backbone router:
var app.myRouteur = Backbone.Router.extend({
routes: {
"todos": "get",
"todo/add": "add",
"todo/update/:id": "update",
"todo/delete/:id" "delete"
},
get: function() {
alert('get route triggered');
},
add: function() {
},
update: function(id) {
},
delete: function(id) {
}
});
The router is instanciated as such:
var app = app || {};
var ENTER_KEY = 13;
$(function() {
new app.myRouteur();
Backbone.history.start({pushState: true, root: "/api/index.php/"});
new app.AppView();
});
My question is: what should I do so that the models automatically use those routes to communicate with the webservice?
Is this router supposed to define the webservice's urls or only backbone internal urls (and then webservice's urls should be declared in the model)?
I'm a bit lost and confused... not knowing what do to with this router...
1- The Router's routes are here just to organize your application and centerlize the workflow between you views. You can access them by tags or using Backbone.History.navigate() ...
2- The responsables of accessing your webservices are models with urlRoot and collections with url

Resources