C#Web API路由与Angular路由混合使用

all*_*ded 5 c# asp.net-mvc angularjs

是否有可能使MVC应用程序仅使用WEB API形式的路由,但是允许angular使用其routeprovider完成剩余的路由?当我运行我的应用程序时,我得到:

GET http://localhost:8080/Views/Home/Index.html 404 (Not Found) 
Run Code Online (Sandbox Code Playgroud)

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" }
        );
Run Code Online (Sandbox Code Playgroud)

WebAPIConfig.cs

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

C#Controller(尝试多种方式)

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();
}
Run Code Online (Sandbox Code Playgroud)

角度路由:

   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: "/" });
});
Run Code Online (Sandbox Code Playgroud)

参考文件结构图片:

在此输入图像描述

编辑:GitHub工作示例:https: //github.com/allencoded/CSharpAngularRouting

Dar*_*n P 6

您应该使用MVC 4/5生成角度应用程序的所有视图.您的主页可以在路由中初始化角度应用程序,您可以使用mvc url为布局设置为null的视图.

编辑:

创建Web Api项目在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" }
);
Run Code Online (Sandbox Code Playgroud)

_ViewStart.cshtml

@{
    Layout = null;
 }
Run Code Online (Sandbox Code Playgroud)

HomeController索引操作页面将是您的角度主页,所有其他可以是您的角度局部视图.

编辑:

你的角度模板网址是错误的.当angular尝试加载模板mvc将返回主页模板(具有ng-app),因此它将再次初始化,并且您只能初始化ng-app一次.

将模板网址更改为 /view/{controller/{action}

 .when("/Tests", { templateUrl: "view/Home/test", controller: "homeCtrl" })
Run Code Online (Sandbox Code Playgroud)