简体   繁体   中英

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

So I'm trying to set up the routing for my project, I have a few different cases that need to be handled but I'm unable to make them work as intended.
case 1: / - Routes to the index of the angular app
Case 2: /{angular Route} - Routes to angulars routing but I'm guessing it first needs to be redirected to angular base page.
Case 3: /api/data/GetAllValues - Routes to the data api controller method and GetAllValues action
My base file for angular is stored at the root: /index.html but I have it so that when you go to this page angular will take you to /Index

This is the routing I have in WebApiConfig.Register which is invoked by the 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"));

And Angular routes

.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' });

I'm getting a few issues with this setup, neither case 1 or 2 work, both result in a message from asp.net with saying that it cannot match a url to the request
Edit: this is the error message when I try navigate to / (case 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/'"}

Update:
I changed the asp.net default route to catch {.*} and now when I put in / it correctly redirects to angular but when I do /Index I am still gettign the error as below
{"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'"}

I'm guessing that you forgot to configure local redirections properly. If you enter /Index in your browser, request is not redirected to your base URL , thus it hits WebAPI instead of Angular.

In your web application web.config I'd add following configuration:

<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>

Additionaly you'd have to set base in your index.html file in the head section like following:

<base href="/" />

While the accepted answer is also needed, I find when you create a web api 2 project it creates an MVC RouteConfig.cs file as well which seems to mess up routing and won't let index.html be the default page for angularjs to start. Since RouteConfig.cs has a route in there (guessing for the help pages) the app when ran on IIS is trying to use that route instead of letting IIS just give the index.html as the default page when no path is specified.

You can remove RouteConfig.cs to get index.html from IIS. The question I'm still working on is how do you get the help pages routed to then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM