Asp.net: WebForm基础上构建Mvc的方法

添加引用:

  • System.Web.Routing
  • System.Web.Abstractions
  • System.Web.Mvc

添加文件夹:

Controllers, ViewsViews / Shared

配置Web.config:是添加配置项,不是直接替换哦!

< ?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="false">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral,
                       PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Extensions,
                       Version=3.5.0.0, Culture=neutral,
                       PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Abstractions,
                       Version=3.5.0.0, Culture=neutral,
                       PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Web.Routing,
                       Version=3.5.0.0, Culture=neutral,
                       PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation> 
    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing"/>
        <add namespace="System.Linq"/>
        <add namespace="System.Collections.Generic"/>
      </namespaces>
    </pages>
    <httpModules>
      <add name="UrlRoutingModule"
           type="System.Web.Routing.UrlRoutingModule,
                 System.Web.Routing, Version=3.5.0.0,
                 Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </httpModules>
  </system.web>
</configuration>

添加路由配置,增加一个Global.asax在根目录下.

重要这句(routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");)把aspx的请求过滤掉.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MixingBothWorldsExample
{
    public class Global : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
            routes.MapRoute(
               "Default",
// Route name
               "{controller}/{action}/{id}",
// URL with parameters
               new { controller = "Home", action = "Index", id = "" }
// Parameter defaults
                );
        }
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

增加编译View的配置:

文本编辑器打开 项目.csproj

<PropertyGroup>中添加已下内容:

<PropertyGroup>
    ...
    <MvcBuildViews>true</MvcBuildViews>

</PropertyGroup>

Target中添加内容

<Target Name="AfterBuild" 
        Condition="'$(MvcBuildViews)'=='true'">
   
   <AspNetCompiler VirtualPath="temp"
                   PhysicalPath="$(ProjectDir)..$(ProjectName)"/>

</Target>

 

MVC和WebForms都是基于这些共同的底层技术实现的:

  • HttpContext
  • Session
  • Server
  • Request
  • Response
  • Cookies

你可能感兴趣的:(Asp.net: WebForm基础上构建Mvc的方法)