ASP.NET 5 HTML5 History

怎甘沉沦 提交于 2019-12-22 04:23:19

问题


I'm upgrading my project to ASPNET5. My application is a AngularJS Web App that uses HTML5 Url Routing ( HTML5 History API ).

In my previous app I used the URL Rewrite IIS Module with code like:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="MainRule" 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}" matchType="Pattern" pattern="api/(.*)" negate="true" />
          <add input="{REQUEST_URI}" matchType="Pattern" pattern="signalr/(.*)" negate="true" />
        </conditions>
        <action type="Rewrite" url="Default.cshtml" />
      </rule>
    </rules>
  </rewrite>
<system.webServer>

I realize I could port this but I want to minimize my windows dependencies. From my reading I think I should be able to use ASP.NET 5 Middleware to accomplish this.

I think the code would look something like this but I think I'm pretty far off.

app.UseFileServer(new FileServerOptions
{
    EnableDefaultFiles = true,
    EnableDirectoryBrowsing = true
});

app.Use(async (context, next) =>
{
    if (context.Request.Path.HasValue && context.Request.Path.Value.Contains("api"))
    {
        await next();
    }
    else
    {
        var redirect = "http://" + context.Request.Host.Value;// + context.Request.Path.Value;
        context.Response.Redirect(redirect);
    }
});

Essentially, I'm wanting to route anything that contains /api or /signalr. Any suggestions on best way to accomplish this in ASPNET5?


回答1:


You were on the right track, but rather than sending back a redirect, we just want to rewrite the path on the Request. The following code is working as of ASP.NET5 RC1.

app.UseIISPlatformHandler();

// This stuff should be routed to angular
var angularRoutes = new[] {"/new", "/detail"};

app.Use(async (context, next) =>
{
    // If the request matches one of those paths, change it.
    // This needs to happen before UseDefaultFiles.
    if (context.Request.Path.HasValue &&
        null !=
        angularRoutes.FirstOrDefault(
        (ar) => context.Request.Path.Value.StartsWith(ar, StringComparison.OrdinalIgnoreCase)))
    {
        context.Request.Path = new PathString("/");
    }

    await next();
});

app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();

One issue here is that you have to specifically code your angular routes into the middleware (or put them in a config file, etc).

Initially, I tried to create a pipeline where after UseDefaultFiles() and UseStaticFiles() had been called, it would check the path, and if the path was not /api, rewrite it and send it back (since anything other than /api should have been handled already). However, I could never get that to work.




回答2:


I'm using:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name:"Everything", 
        template:"{*UrlInfo}", 
        defaults:new {controller = "Home", action = "Index"});
}

This will cause all routes to hit the Home Index page. When I need routes to fall outside this, I add them before this route as this becomes a catch all route.




回答3:


Why not use routing feature in MVC? In the Configure method in Startup.cs, you could modify the following:

        // inside Configure method in Startup.cs
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}/{id?}",
                defaults: new { controller = "Home", action = "Index" });

            // Uncomment the following line to add a route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        });  


来源:https://stackoverflow.com/questions/31184446/asp-net-5-html5-history

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!