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

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 发布常见问题的更多相关文章

  1. (读书笔记)Asp.net Mvc 与WebForm 混合开发

    根据项目实际需求,有时候会想在项目中实现Asp.net Mvc与Webform 混合开发,比如前台框架用MVC,后台框架用WebForm.其实要是实现也很简单,如下: (1)在MVC 中使用Webfo ...

  2. Asp.net Mvc 与WebForm 混合开发

      根据项目实际需求,有时候会想在项目中实现Asp.net Mvc与Webform 混合开发,比如前台框架用MVC,后台框架用WebForm.其实要是实现也很简单,如下: (1)在MVC 中使用Web ...

  3. [转]Asp.net Mvc 与WebForm 混合开发

    本文转自:https://www.cnblogs.com/dooom/archive/2010/10/17/1853820.html 根据项目实际需求,有时候会想在项目中实现Asp.net Mvc与W ...

  4. Taurus.MVC 2.2.3.4 :WebAPI 实现权限控制认证(及功能增强说明)

    前言: 前两天,当我还在老家收拾行旅,准备回广州,为IT连的创业再战365天时, 有网友扣上问:Taurus.MVC中如何实现认证和权限控制,最好能做个小例子. 我一不小心回了句:等回广州我再写篇文章 ...

  5. webform中使用webapi,并且使用autofac

    private void AutofacIoCRegister() { HttpConfiguration config = GlobalConfiguration.Configuration; if ...

  6. NET Core MVC 在linux上的创建及发布

    NET Core MVC 在linux上的创建及发布 前言 ASP.NET core转眼都发布半月多了,社区最近也是非常活跃,虽然最近从事python工作,但也一直对.NET念念不忘,看过了园区大神们 ...

  7. WebApi发布到外网提示404问题

    今天在做微信接口的对接,需要把webApi发布到服务器,放上去的时候,提示404 找了以后,发现了这段代码,粘贴上去就可以用了 在web.config添加如下节点 <system.webServ ...

  8. webapi发布常见错误及解决方案

    webapi发布常见错误及解决方案 错误一: 错误:404 (Not Found) 解决方案: 在  <system.webServer>节点中添加如下模块: <modules ru ...

  9. 如何将dotnet core webapi发布到docker中…

    如何将dotnet core webapi发布到docker中 今天想起来撸一下docker,中途还是遇到些问题,但是这些问题都是由于路径什么的导致不正确,在这儿还是记录下操作过程,今天是基于wind ...

随机推荐

  1. linux服务之audit

    http://blog.chinaunix.net/uid-20786165-id-3167391.html http://blog.chinaunix.net/uid-8389195-id-1741 ...

  2. [Asp.net]说说密码框和只读框

    作者:Wolfy出处:http://www.cnblogs.com/wolf-sun/ 引言 最近负责了一个公司的小项目,从前台到后代,都是自己搞的,为一个客户弄一个信息管理的小系统,虽然对界面什么的 ...

  3. ios 获取屏幕的属性和宽度

    app尺寸,去掉状态栏 CGRect r = [ UIScreen mainScreen ].applicationFrame; r=0,20,320,460 屏幕尺寸 CGRect rx = [ U ...

  4. IIS不定期Crash和Oracle“未处理的内部错误(-2)”的问题分析

    问题描述:系统不定期报出Oracle“未处理的内部错误(-2)”,严重时IIS会Crash 典型异常日志如下: Exception type:   System.AccessViolationExce ...

  5. 数据库连接工具类——包含取得连接和关闭资源 ConnUtil.java

    package com.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Prepare ...

  6. [mybatis] mybatis错误:Invalid bound statement (not found)

    点击菜单抛出异常: org.springframework.web.util.NestedServletException: Request processing failed; nested exc ...

  7. 给Jquery动态添加的元素添加事件2

    $('div').on('click', 'button', function(e){console.log($(e.target).is(':button'))}); $('<button&g ...

  8. 【Spring学习笔记-6】关于@Autowired与@Scope(BeanDefination.SCOPE_PROTOTYPE)

    当类被@Scope(BeanDefination.SCOPE_PROTOTYPE)修饰时,说明每次依赖注入时,都会产生新的对象,具体可参见文章:http://blog.csdn.net/gst6062 ...

  9. Python标准库

    Python标准库是随Python附带安装的,它包含大量极其有用的模块.熟悉Python标准库是十分重要的,因为如果你熟悉这些库中的模块,那么你的大多数问题都可以简单快捷地使用它们来解决. sys模块 ...

  10. No Suitable Driver Found For Jdbc_我的解决方法

    转载自:http://www.blogjava.net/w2gavin/articles/217864.html      今天出现编码出现了No suitable driver found for ...