c# 编写能跨域的Web API

服务器端

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方法在跨域中还是被拒绝的,尝试将发布网站的应用程序池的托管管道模式改成“集成”




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值