MVC 4 与WebForm 混合应用 WebApi 发布常见问题

1、所有应用的MVC相关程序集编译时要选择复制到本地,需要用到的程序如下图

MVC 4 与WebForm 混合应用 WebApi 发布常见问题_第1张图片

2、IIS设置:

因为 IIS 7/8 采用了更安全的 web.config 管理机制,默认情况下会锁住配置项不允许更改。运行命令行 %windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/handlers 。
其中的 handlers 是错误信息中红字显示的节点名称。
如果modules也被锁定,可以运行%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/modules

注意:cmd.exe要以管理员身份启动,在c:\windows\system32下找到cmd.exe,右键管理员启动,输入上面的命令即可。

3、配置文件修改,添加MVC对应配置

<?xml version="1.0" encoding="utf-8"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false"/>
            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false"/>
        </sectionGroup>
    </configSections>
    <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <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.Web.Optimization"/>
                <add namespace="System.Linq"/>
                <add namespace="System.Collections.Generic"/>
            </namespaces>
        </pages>
    </system.web.webPages.razor>
    <appSettings>
        
    </appSettings>

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
        <!--<assemblies>
            <add assembly="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </assemblies>-->
        <httpHandlers>
        </httpHandlers>
        <pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
            <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>

    </system.web>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />

     
    </system.webServer>

</configuration>

3、路由设置:

 protected void Application_Start(object sender, EventArgs e)
        {
            RouteCollection routes = RouteTable.Routes;

            //避免对 Web 资源文件(例如 WebResource.axd 或 ScriptResource.axd)的请求传递给控制器  
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //避免aspx页面的请求传递给控制器
            routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
            routes.IgnoreRoute("{handler}.ashx/{*pathInfo}");
            routes.IgnoreRoute("ajaxpro/prototype.ashx");
            routes.IgnoreRoute("ajaxpro/core.ashx");
            routes.IgnoreRoute("ajaxpro/converter.ashx");
            routes.IgnoreRoute("ajaxpro/{resource}.ashx");

            routes.IgnoreRoute("{resource}.asmx/{*pathInfo}");

        


            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //路由注册
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
            HttpConfiguration config = GlobalConfiguration.Configuration;
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
        }

 4、自定义WebApi 带方法的路由

    routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

5、用get post ajax请求 webapi方法:

WebApi中定义的方法:

 public class ItemController : ApiController
    {
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        public string Get(int id)
        {
            Result res = new Result { Id = id, IsOK = true, Message = "测试成功。" };
            return JsonConvert.SerializeObject(res);
            //return res;
        }
        [HttpGet]
        public string TestData(int id, string message)
        {
            Result res = new Result { Id = id, IsOK = true, Message = message };
            return JsonConvert.SerializeObject(res);
        }

        public string SaveData([FromBody]Result data)
        {
            Result res = new Result { Id = data.Id, IsOK = true, Message = data.Message };
            return JsonConvert.SerializeObject(res);
            //return string.Empty;
        }
    }


    public class Result
    {
        public int Id
        {
            get;
            set;
        }

        public bool IsOK
        {
            get;
            set;
        }
        public string Message
        {
            get;
            set;
        }
    }

 

AJAX调用

 

 $.ajax({
                url: "api/item/get/1",
                type: "get",
               // data: { "": 1 },
                success: function (data) {
                    alert(data);
                }
            });

 

 $.ajax({
                url: "api/item/SaveData",
                type: "post",
                data: JSON.stringify({ id: 1, message: "测试ok?" }),
                contentType: "application/json",
                success: function (data) {
                    alert(data);
                }
            });

 

 

附上程序源码:http://pan.baidu.com/s/1c0e71Xe

你可能感兴趣的:(MVC 4 与WebForm 混合应用 WebApi 发布常见问题)