在ASP.NET Web API 2项目中设置Angular路由

Setting up Routing for Angular in a ASP.NET Web API 2 project

本文关键字:设置 Angular 路由 项目 ASP NET Web API      更新时间:2023-09-26

所以我正在尝试为我的项目设置路由,我有一些不同的情况需要处理,但我无法使它们按预期工作
案例1:/-到angular应用程序索引的路径
情况2:/{angular Route}-路由到angular路由,但我猜它首先需要重定向到angular基页
案例3:/api/data/GetAllValues-路由到data-api控制器方法和GetAllValues操作
我的angular基本文件存储在根目录:/index.html,但我有它,所以当你转到这个页面时,angular会把你带到/Index

这是我在WebApiConfig.Register中的路由,由Global.asax 调用

config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
    name: "DefaultActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute("AngularRedirect", "{.*}", "~/index.html");
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

和角度路线

.config(function($routeProvider, $locationProvider) {
    $routeProvider.when('/Index',
        {
            templateUrl: 'Templates/Feed.html',
            controller: 'feedController'
        }
    );
    $routeProvider.when('/Lookup',
        {
            templateUrl: 'Templates/Lookup.html',
            controller: 'lookupController'
        }
    );
   $locationProvider.html5Mode(true);
   $routeProvider.otherwise({ redirectTo: '/Index' });

我在这个设置中遇到了一些问题,情况1或2都不起作用,都会导致asp.net发出一条消息,说它无法将url与请求相匹配
编辑:这是我尝试导航到/(情况1)时的错误消息

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:49569/'.","MessageDetail":"No route providing a controller name was found to match request URI 'http://localhost:49569/'"}

更新:
我将asp.net默认路由更改为catch{.*},现在当我放入/时,它正确地重定向到angular,但当我执行/Index时,我仍然会得到如下错误
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:49569/Index'.","MessageDetail":"No route providing a controller name was found to match request URI 'http://localhost:49569/Index'"}

我猜您忘记正确配置本地重定向了。若您在浏览器中输入/Index,请求不会重定向到您的基本URL,因此它会访问WebAPI而不是Angular。

在您的web应用程序web.config中,我会添加以下配置:

<system.webServer>
    <rewrite>
      <rules>
        <rule name="AngularJS" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

此外,您必须在head部分的index.html文件中设置base,如下所示:

<base href="/" />

虽然也需要接受的答案,但我发现当你创建一个web api 2项目时,它也会创建一个MVC RouteConfig.cs文件,这似乎会打乱路由,并且不会让index.html成为angularjs启动的默认页面。由于RouteConfig.cs中有一个路由(猜测帮助页面),因此在IIS上运行应用程序时,会尝试使用该路由,而不是在未指定路径时让IIS仅将index.html作为默认页面。

您可以删除RouteConfig.cs以从IIS获取index.html。我仍在研究的问题是,如何将帮助页面发送到那里。