using $stateProvider with asp.net web api - angularjs

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.

Related

A web page is slowing down your browser, it is waiting for csi.gstatic.com

I have written web application on .net 2017 c#, I had to change my URL to simpler in order to get rid of ? or = from URL and also I am using Google Map on my web site. When I click to records which will be redirected and changed to other link, I got this error.
Original url is: mydomain.com/Doctor?id=XX
I converted it to: mydomain.com/Doctor/XX
I did it by defining new MapRoute on RegisterRoutes as:
RouteCofig.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Blog", // Route name
"Doctor/{id}", // URL with parameters
new { controller = "Home", action = "PersianDR", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I also used angularjs:
Angular Module:
var app = angular.module('MyApp', ['ngRoute', 'uiGmapgoogle-maps', 'nemLogging', 'ngSanitize']);
app.config(['$routeProvider', '$locationProvider', function ($routeprovider, $locationProvider) {
$routeprovider.
when('/Home/PersianDR/:id', {
templateurl: '/Views/Home/PersianDR.cshtml',
controller: 'AngularCtrl_ShowDr'
})
.
when('Doctor/:id', {
redirectto: '/Home/PersianDR/:id'
})
.
otherwise({
redirectto: '/'
})
;
//$locationProvider.html5Mode(true);
$locationProvider.html5Mode({
enabled: true,
rewriteLinks: false
});
}]);
Angular Controller:
app.controller("AngularCtrl_ShowDr", function ($scope, $location, angularService_ShowDr, $route, $routeParams, $http, $sce) {
var docId = $("#myId").val();
$location.path();
$location.url('Doctor/' + docId).replace();
GetDoctorByID();
GetGeoCoordinates();
maps();
});
This problem as been started since I changed URL.
I finally found an interesting answer.
There is a conflict when I wanted to redirect and make my url simple while I am using google map apis, this is because gmap needs absolute path or url while I wanted to change my url simple and elegant.
What I did to remove holding on waiting to load csi.gstatic.com, was to use partial view.
I totally brought my ui-gmap-google-map inside partial view and called it from original one.
In original page.cshtml:
#Html.Partial("_MapDoctor")
In partial view , _MapDoctor.cshtml:
<div ng-controller="AngularCtrl_MapDr">
<input type="hidden" id="myId2" value="#ViewBag.id" />
<ui-gmap-google-map center='mapsdrsec.center' zoom='mapsdrsec.zoom' options='mapsdrsec.options'>
<ui-gmap-layer type="TrafficLayer" show="mapsdrsec.showTraficLayer"></ui-gmap-layer>
<ui-gmap-markers models="markers" idkey="markers.id" coords="'coords'">
</ui-gmap-markers>
</ui-gmap-google-map>
</div>
I wrote specified controller and services in angularjs for partial view. I deleted filling $scope.map from original and wrote (center, zoom, options, $scope.markers ) in partial view controller.

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

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" }
);
}
}

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" }
);
});

jHipster - AngularJS route redirects to login even when authorities are removed from entity

By default jHipster generated entities are accessable for ROLE_USER.
I would like to create entity which can be accessible even for unregistred/unauthorized users.
Let's call the entity: Company
What I've done is removal of ROLE_USER from authorities array in every state in company.js. I can enter the entity (companys) page by going to http://localhost:3000/#/companys (I can see it for a second) but angular automatically redirects to login view (http://localhost:3000/#/login).
I believe the behaviour of this routing is somewhere defined in jHipster however I cannot find it. Any hints for angular newbie? :)
UPDATED
Here is piece of config where I removed authorities:
angular.module('testApp')
.config(function ($stateProvider) {
$stateProvider
.state('company', {
parent: 'entity',
url: '/companys',
data: {
authorities: [], <---- here I removed 'ROLE_USER'
pageTitle: 'testApp.company.home.title'
},
views: {
'content#': {
templateUrl: 'scripts/app/entities/company/companys.html',
controller: 'CompanyController'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('company');
$translatePartialLoader.addPart('companyType');
$translatePartialLoader.addPart('global');
return $translate.refresh();
}]
}
})
Try this way at the com.company.config.SecurityConfiguration because this will permit all including the unregistered:
.disable()
.and()
.authorizeRequests()
.antMatchers("/company/**").permitAll() // <<<<< ADD THIS

Requestmapping from angular-ui-router and spring mvc

I am using AngulaJS as a javascript client side and spring mvc as a rest backend.
In AngulaJS i am using ui-router.
Here is config.js file
function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/index");
$stateProvider
.state('trains', {
url: "/trains",
templateUrl: "views/pages/trains.html",
data: {
pageTitle: 'Trains'
}
})
Below is html file (left-sliderbar.html
<li ui-sref-active="active">
Trains
</li>
The problem is when I clicked on "Trains" menu in left left-sliderbar, I cannot get request mapping with the method in Rest Backend of Spring MVC. Below is code from Controller of Spring MVC
#RequestMapping("/trains")
public String getTrainPartialPage(ModelMap modelMap) {
System.out.println("---------Request Mapping: /trains: " + this.getClass());
return "pages/trains";
}
Please help me to fix it out, I'd like to use ui-router than ngRoute, thanks you
function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/index");
$stateProvider
.state('trains', {
url: "/trains",
data: {
pageTitle: 'Trains'
},views: {
'content#': {
templateUrl: "views/pages/trains.html",
controller: 'TrainsController'
}
}
})
and you need to implement the rest calls in your service or in your TrainsController.
I had the same problem in a same context.
I think you shoud try to use templateUrl: "views/pages/trains" instead of templateUrl: "views/pages/trains.html" in your $stateProvider provider.
The back-end controller should expose this request mapping:
#RequestMapping(value = "/train")
public ModelAndView getMain() {
return new ModelAndView("pages/train");
}
NB: Using ModelAndView as a return object instead of String (didn't worked with String and actually I con't figure why).
Angular UI Router will write /train in the url and Spring will serve the html file mapped on the /train route.
Hope will help you.

Resources