C # web API routing blended with Angular routing

Is it possible to use an MVC app to only be used in a WEB API form, but then let angular do the rest of the routing with its router? When I run my application I get:

GET http://localhost:8080/Views/Home/Index.html 404 (Not Found) 

      

MVC Route RouteConfig.Cs

 // serves plain html
        routes.MapRoute(
             name: "DefaultViews",
             url: "view/{controller}/{action}/{id}",
             defaults: new { id = UrlParameter.Optional }
        );

        // Home Index page have ng-app
        routes.MapRoute(
            name: "AngularApp",
            url: "{*.}",
            defaults: new { controller = "Home", action = "Index" }
        );

      

WebAPIConfig.cs

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

      

C # controller (multiple attempts)

public ActionResult Index()
{
    ViewBag.Title = "Home Page";

    return View();
}

public ActionResult Test()
{
    var result = new FilePathResult("~/Views/Home/test.html", "text/html");
    return result;
}

public ActionResult Show()
{
    ViewBag.Title = "HomePage";

    return View();
}

      

Angular routing:

   app.config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    $routeProvider
        .when("/Tests", { templateUrl: "Views/Home/test.html", controller: "homeCtrl" })
        .when("/Shows", { templateUrl: "/Home/Show.cshtml", controller: "homeCtrl" })
        .otherwise({ redirectTo: "/" });
});

      

File structure picture for reference:

enter image description here

EDIT: Working GitHub example: https://github.com/allencoded/CSharpAngularRouting

+3


source to share


1 answer


You should be using MVC 4/5 to create the whole view for your angular app. Your home page can initialize angular app and then in your routes, you can use mvc url for your views with layout set to null.

EDIT:

Create Web Project Api Add this to RouteConfig.cs

// serves plane html
routes.MapRoute(
     name: "DefaultViews",
     url: "view/{controller}/{action}/{id}",
     defaults: new { id = UrlParameter.Optional }
);

// Home Index page have ng-app
routes.MapRoute(
    name: "AngularApp",
    url: "{*.}",
    defaults: new { controller = "Home", action = "Index" }
);

      

_ViewStart.cshtml

@{
    Layout = null;
 }

      



The "Control Home" page will be your angular home page and all others can be partial angular views.

EDIT:

Your template template in angular is wrong. When angular tries to load the template, mvc will return the home page template (with ng-app) to initialize again and you can only initialize ng-app once.

Change the url of the template to /view/{controller/{action}

 .when("/Tests", { templateUrl: "view/Home/test", controller: "homeCtrl" })

      

+4


source







All Articles