ASP.NET Core Route Change

一笑奈何 提交于 2019-12-08 08:10:33

问题


I need to update a handful of static web pages, and I would like to take this time to recreate them using ASP.NET Core (ASP.NET 5 with MVC 6) in Visual Studio 2015. I want to rebuild it using Microsoft's latest technology to make changes easier in the future.

When I start the project on localhost, the default website loads up fine but any of the linked pages break because they route to the /Home controller by default. Also, none of the project's jquery, css or images are found when MVC nests these pages.

In the file Startup.cs, there is the following method:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseIdentity();

    // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

This is how it comes configured out of the box.

Our company does not want /Home (or anything else) stuck on the URL of all of their web pages.

I have created various IActionResult methods for the different pages, but all of them do the same thing:

public IActionResult Index()
{
    return View();
}

We also have companies that link to our website. Changing the structure of our pages is going to cause other companies to stop and make changes, too.

How would I take a string, such as {controller}/{action}/{id?}, and have that return a typical link, such as action.aspx?id=x?

Alternately, is there a way to tell MVC not to use a template for certain pages?

I apologize if this is stupid basic. I generally work on Windows Forms.


回答1:


There are two solutions:

Route Template:

app.UseMvc(routes =>
{
    routes.MapRoute(
        "HomeRoute", 
        "{action}/{id}", 
        new 
        { 
            controller = "Home", 
            action = "Index", 
            id = UrlParameter.Optional
        });
});

Attribute Routes

[HttpGet("")]
public IActionResult Index()
{
    return View();
}

You can create a new project using ASP.NET MVC Boilerplate for a full working example using this method.



来源:https://stackoverflow.com/questions/37928214/asp-net-core-route-change

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