How to route EVERYTHING other than Web API to /index.html

后端 未结 6 478
春和景丽
春和景丽 2020-12-04 12:49

I\'ve been working on an AngularJS project, inside of ASP.NET MVC using Web API. It works great except when you try to go directly to an angular routed URL

相关标签:
6条回答
  • 2020-12-04 13:32

    Suggest more native approach

    <system.webServer>
        <httpErrors errorMode="Custom">
            <remove statusCode="404" subStatusCode="-1"/>
            <error statusCode="404" prefixLanguageFilePath="" path="/index.cshtml" responseMode="ExecuteURL"/>
        </httpErrors>
    </system.webServer>
    
    0 讨论(0)
  • 2020-12-04 13:33

    Well, I just removed the RouteConfig.RegisterRoutes(RouteTable.Routes); call in Global.asax.cs and now whatever url I enter, if the resource exists, it will be served. Even the API Help Pages still work.

    0 讨论(0)
  • 2020-12-04 13:37

    Use a wildcard segment:

    routes.MapRoute(
        name: "Default",
        url: "{*anything}",
        defaults: new { controller = "Home", action = "Index" }
    );
    
    0 讨论(0)
  • 2020-12-04 13:39

    in my case none of these approaches worked. i was stuck in 2 error message hell. either this type of page is not served or some sort of 404.

    url rewrite worked:

    <system.webServer>
        <rewrite>
          <rules>
            <rule name="AngularJS" stopProcessing="true">
              <match url="[a-zA-Z]*" />
    
              <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>
        ...
    

    notice i matched on [a-zA-Z] because i don't want to rewrite any of the .js .map etc urls.

    this worked in VS out of hte box, but in IIS you may need to install a url-rewrite module https://www.iis.net/downloads/microsoft/url-rewrite

    0 讨论(0)
  • 2020-12-04 13:52

    I've been working with OWIN Self-Host and React Router few days ago, and incurred to probably similar issue. Here is my solution.

    My workaround is simple; check if it's a file in the system; otherwise return index.html. Since you don't always want to return index.html if some other static files are requested.

    In your Web API config file:

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

    and then create a HomeController as follwing...

    public class HomeController: ApiController
    {
        [HttpGet]
        [ActionName("Index")]
        public HttpResponseMessage Index()
        {
            var requestPath = Request.RequestUri.AbsolutePath;
            var filepath = "/path/to/your/directory" + requestPath;
    
            // if the requested file exists in the system
            if (File.Exists(filepath))
            {
                var mime = MimeMapping.GetMimeMapping(filepath);
                var response = new HttpResponseMessage();
                response.Content = new ByteArrayContent(File.ReadAllBytes(filepath));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue(mime);
                return response;
            }
            else
            {
                var path = "/path/to/your/directory/index.html";
                var response = new HttpResponseMessage();
                response.Content = new StringContent(File.ReadAllText(path));
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                return response;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-04 13:54

    I had a similar approach as the top few answers, but the downside is if someone is making an API call incorrectly, they'll end up getting that index page back instead of something more useful.

    So I've updated mine such that it will return my index page for any request not starting with /api:

            //Web Api
            GlobalConfiguration.Configure(config =>
            {
                config.MapHttpAttributeRoutes();
            });
    
            //MVC
            RouteTable.Routes.Ignore("api/{*anything}");
            RouteTable.Routes.MapPageRoute("AnythingNonApi", "{*url}", "~/wwwroot/index.html");
    
    0 讨论(0)
提交回复
热议问题