System.Web.Http.Cors配置跨域访问

System.Web.Http.Cors配置跨域访问的两种方式
  使用System.Web.Http.Cors配置跨域访问,众多大神已经发布了很多文章,我就不在详细描述了,作为小白我只说一下自己的使用心得。在webapi中使用System.Web.Http.Cors配置跨域信息可以有两种方式。
  一种是在App_Start.WebApiConfig.cs的Register中配置如下代码,这种方式将在所有的webapi Controller里面起作用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace YDTG.Service
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务

// Web API 路由
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//这是重点,从配置文件的appsettings节点中读取跨域的地址
var cors = new EnableCorsAttribute(ConfigurationManager.AppSettings["origins"], "*", "*");
config.EnableCors(cors);
}
}
}
配置文件如下,注意一定要加上http

<add key="origins" value="http://localhost:9012,http://192.168.1.108:9012" />
1
  第二种方式就是在每个webapiController类中设置,即每个控制器个性化配置,如下代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Cors;
using System.Web.Mvc;

namespace Service.Controllers
{
[EnableCors("http://localhost:9012,http://192.168.1.108:9012", "*", "*")]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";

return View();
}
}
}
注意事项
EnableCors共三个参数分别为origins、headers和methods。origins配置允许访问的域名,多个域名以逗号分隔即可,域名一定要完整,如果是ip地址前面要加上“http”,只使用IP的话一定会失效的。参数headers配置所支持的资源。参数methods配置支持的方法,get、post、put等。如果允许任意域名、任意资源、任意方法访问自己的webapi,则三个参数全部使用星号”*”即可。
“EnableCors(“http://localhost:9012,http://192.168.1.108:9012“, ““, ““)”中的配置如果出现错误的话不会报错,而是直接禁止未出现在配置表中的资源访问。
如果使用第一种方式那么可以从配置文件中读取网站列表,如果使用第二种方式,所有的参数只能使用常量。
---------------------
原文:https://blog.csdn.net/chaoyangzhixue/article/details/52251322

猜你喜欢

转载自www.cnblogs.com/wmqBlog/p/10112338.html