服务器端
1)创建能够被跨域调用的Web API 参考文章http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
在VS2012中创建ASP.NET MVC 4 Web 应用程序,选择项目模版Web API。
接下来选择“工具”,“库程序包管理器”,“程序包管理器控制台”,然后在控制台输入命令行:Install-Package Microsoft.AspNet.WebApi.Cors
运行程序如果程序报如下错误:System.Web.Http.GlobalConfiguration”的类型初始值设定项引发异常。
就在控制台输入命令行:Update-Package Microsoft.AspNet.WebApi -Pre
接下来运行程序应该不会报错了。
打开 App_Start/WebApiConfig.cs文件。 将代码config.EnableCors(); 添加到WebApiConfig.Register方
法中,WebApiConfig.cs代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace MvcApplication7
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
为控制器(ValuesController)添加[EnableCors]属性代码:[EnableCors(origins: "*", headers: "*", methods: "*")]
ValuesController.cs代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace MvcApplication7.Controllers
{
/// <summary>
/// 1) The origins parameter of the [EnableCors] attribute specifies which origins are allowed to access the resource.
/// The value is a comma-separated list of the allowed origins.
/// You can also use the wildcard value “*” to allow requests from any origins.
/// 2) The methods parameter of the [EnableCors] attribute specifies which HTTP methods are allowed to access the resource.
/// To allow all methods, use the wildcard value “*”.
/// </summary>
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ValuesController : ApiController
{
}
}
提示:Jquery调用Web api的PUT方法和DELETE方法在跨域中还是被拒绝的,尝试将发布网站的应用程序池的托管管道模式改成“集成”