为什么ASP.NET Core,区域中的属性路由不起作用

时间:2018-03-22 21:53:11

标签: c# asp.net-core routing attributerouting

我创建了一个空项目。

Startup.cs

public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).AddDataAnnotationsLocalization();

            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                new CultureInfo("en-US"),
                new CultureInfo("de-DE"),
                new CultureInfo("tr-TR"),
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
                // options.RequestCultureProviders = new List<IRequestCultureProvider> { new CookieRequestCultureProvider() };
            });

            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            var localizationOption = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();

            app.UseRequestLocalization(localizationOption.Value);

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

            app.UseStaticFiles();

            app.UseMvc();
        }
    }

文件夹结构

Project
|
|--Areas 
|---Profile
|----Controllers
|         HomeController
|       

的HomeController

[Area("Profile")]
public class HomeController : Controller
{
    [Route("About")]
    public IActionResult About()
    {
        return View();
    }
}

我是关于asp.net核心的新手,我只是想了解,这个网址“http://localhost:41036/profile/about”总是返回“ 404 not found ”,这有点令人困惑。我做错了什么?如果你帮助我,我会很高兴。

1 个答案:

答案 0 :(得分:3)

您需要Startup区域的路线。

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

您需要向控制器类添加路由属性。

[Area("Profile")]
[Route("[area]/[controller]")]
public class HomeController : Controller 
{
}