创建一个Mvc项目 域名:http://localhost:24102
Home控制器
using MvcApp.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApp.Controllers { [AllowCors("http://localhost:13433","http://localhost:13435")] //[AllowCors] public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Test() { var json = new { Name = "Server" }; return Json(json,JsonRequestBehavior.AllowGet); } } }定义一个特性AllowCorsAttribute
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApp.Filters { public class AllowCorsAttribute:ActionFilterAttribute { private string[] _domains; public AllowCorsAttribute() { //如果[AllowCors]特性标签没有带域名,那么就从配置文件中读取允许访问的域名,然后将它赋给_domains //_domains = 这里应该是从配置文件中读出来的所有域名组成的数组 _domains = new string[] { "","" }; } public AllowCorsAttribute(params string[] domain) { _domains = domain; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var urlReferrer = filterContext.HttpContext.Request.UrlReferrer; if (urlReferrer != null) { var absolutePath = urlReferrer.OriginalString; var absolutePathFormat = absolutePath.Substring(0,absolutePath.Length - 1); if (_domains.Contains(absolutePathFormat)) { filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin",absolutePathFormat); } } else { //如果urlReferrer为空,我理解为自己本地访问(亲自测试,本地访问urlReferrer为null) filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin","*"); } filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods","GET,HEAD,OPTIONS,POST,PUT"); filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers","Access-Control-Allow-Headers,Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers"); base.OnActionExecuting(filterContext); } } }
在创建一个客户端项目(域名:http://localhost:13433),并在这个客户端项目中用ajax来访问这个控制器
@{ ViewBag.Title = "Index"; } <h2>Index</h2> <script type="text/javascript"> $.ajax({ url: 'http://localhost:24102/Home/Test',type: 'Post',success: function (data,textStatus) { alert(data.Name); },error:function(XMLHttpRequest,textStatus,errorThrown){ alert(XMLHttpRequest.state); } }) </script>原文链接:https://www.f2er.com/ajax/161600.html