【问题标题】:How should I handle MVC and WebAPI routing for a SPA with one index.cshtml page?我应该如何处理带有一个 index.cshtml 页面的 SPA 的 MVC 和 WebAPI 路由?
【发布时间】:2014-06-10 14:56:41
【问题描述】:

我有一个单页应用程序,它有一个 MVC 文件 index.cshtml 由 Home 控制器和 Index 方法提供服务。所有登录、注销 和数据请求由 WebAPI 提供服务。有人可以确认我是否正在设置 我的路由正确。这是我所拥有的:

RouteConfig.cs

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

        routes.MapRoute("DefaultRedirect",
            "",
            new { controller = "Home", action = "Index" }
        );

        routes.MapRoute(
            "catchall",
            url: "{*url}",
            defaults: new { controller = "Home", action = "Index" });

    }

WebApiConfig.cs

    public static void Register(HttpConfiguration config)
    {

        config.Routes.MapHttpRoute(
            name: ApiControllerOnly,
            routeTemplate: "api/{controller}"
            );

        config.Routes.MapHttpRoute(
            name: ApiControllerAndId,
            routeTemplate: "api/{controller}/{id}",
            defaults: null, //defaults: new { id = RouteParameter.Optional } //,
            constraints: new { id = @"^\d+$" } // id must be all digits
            );

        config.Routes.MapHttpRoute(
            name: ApiControllerAction,
            routeTemplate: "api/{controller}/{action}"
            );

        config.Routes.MapHttpRoute(
            name: ApiControllerActionAndId,
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: null, //defaults: new { id = RouteParameter.Optional } //,
            constraints: new { id = @"^\d+$" }
            );

    }

全球.asax

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        WebApiConfig.CustomizeConfig(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

我不确定的是第一个处理 MVC 路由的文件。我需要有吗 只有一条路线可以让一切都转到 Home Controller 和 Index 方法。

我还应该在 MVC 路由中忽略那些以 api 开头的请求吗?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-mvc-routing


    【解决方案1】:

    您不应该将您的 SPA 页面作为 index.cshtml 提供(因为这意味着它正在被编译为服务器上将提供响应的相应类)

    它应该作为 index.html 提供,并且它需要的所有数据都应该通过 AJAX 调用来获取到服务器。

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 2015-02-01
      • 2016-10-28
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      相关资源
      最近更新 更多