加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何使用app_start或webactivator注册区域?

发布时间:2020-12-16 07:41:17 所属栏目:asp.Net 来源:网络整理
导读:我想避免打电话 AreaRegistration.RegisterAllAreas() 在我的global.asax中,因为我试图将所有启动逻辑移动到App_Start文件夹中的各个类中.但是,我没有成功地让它发挥作用.第一个选项尝试使用这样的代码: [assembly: PreApplicationStartMethod(typeof(Start
我想避免打电话

AreaRegistration.RegisterAllAreas()

在我的global.asax中,因为我试图将所有启动逻辑移动到App_Start文件夹中的各个类中.但是,我没有成功地让它发挥作用.第一个选项尝试使用这样的代码:

[assembly: PreApplicationStartMethod(typeof(Startup),"PreInit")]
namespace Foo
{
  public class Startup {}
}

PreApplicationStartMethod来自System.Web名称空间的位置.在这种情况下,对寄存器区域的调用过早发生.

第二种方法基于this post by David Ebbo,使用WebActivator:
使用System.Web.Mvc;

[assembly: WebActivatorEx.PostApplicationStartMethod
(typeof(AreaDemo.AreaConfig),"RegisterAreas")]
    namespace AreaDemo
    {
        public class AreaConfig
        {
            public static void RegisterAreas()
            {
                AreaRegistration.RegisterAllAreas();
            }
        }
    }

不幸的是,尽管没有抛出错误,但尝试导航到该区域失败(好像注册从未发生过).

使用程序集指令而不是从Global.asax直接调用,从启动类中注册ASP.NET MVC 5中的区域的正确方法是什么?

更新1:这是我的AreaRegistration代码:

public class AdminAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Admin";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Admin_default","Admin/{controller}/{action}/{id}",new { controller = "Home",action = "Index",id = UrlParameter.Optional },new string[] { "AreaDemo.Areas.Admin.Controllers" }
            );
    }
}

由于某种原因,默认值被忽略,但导航到/ admin / home / index / 0有效. / admin,/ admin / home和/ admin / home / index全部404.

解决方法

我认为这是一个订购问题(你似乎也怀疑它).我认为这些区域在Application_Start事件之后被注册,因此区域的路线在非区域路线之后被注册.

4段URL(/ admin / home / index / 123)工作的原因是它无法匹配MVC应用程序的“默认”路由.因此,跳过该默认路由(因为它仅匹配1,2和3段URL),并且路由将找到可以处理4段URL的区域特定路由. 1段,2段或3段URL将与非区域路由匹配,但当然在区域之外没有控制器来处理这样的URL,因此返回404.

如果我理解正确,您希望在Application_Start之后注册区域,但在“其他”发生之前?不幸的是,我不知道有任何特定的事件要处理.从IHttpModule你可以尝试处理一个事件,比如BeginRequest,这个事件超级发生,很快只在那里注册一次(也就是说,不要在每个请求上注册东西!),这应该允许你潜入在ASP.NET Routing之前做了什么(在PostResolveRequestCache期间稍后发生).

一个完全替代方案是使用attribute routes,许多人喜欢它,因为它可以帮助避免订购问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读