标签:
using System.Web; using System.Web.Http.Filters; using System.Web.Mvc; namespace APIApplication { public class CrossSiteAttribute : System.Web.Http.Filters.ActionFilterAttribute { private const string Origin = "Origin"; /// <summary> /// Access-Control-Allow-Origin是HTML5中定义的一种服务器端返回Response header,用来解决资源(比如字体)的跨域权限问题。 /// </summary> private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin" ; /// <summary> /// originHeaderdefault的值可以使 URL 或 *,如果是 URL 则只会允许来自该 URL 的请求,* 则允许任何域的请求 /// </summary> private const string originHeaderdefault = "*" ; /// <summary> /// 该方法允许api支持跨域调用 /// </summary> /// <param name="actionExecutedContext"> 初始化 System.Web.Http.Filters.HttpActionExecutedContext 类的新实例。</param> public override void OnActionExecuted( HttpActionExecutedContext actionExecutedContext) { actionExecutedContext.Response.Headers.Add(AccessControlAllowOrigin, originHeaderdefault); } } }
private HttpClient client = new HttpClient(); private string url = "http://localhost:12622/api/company/get"; public async Task<ActionResult> Index() { var data = await client.GetAsync(url); var comm = data.Content.ReadAsAsync<IEnumerable<v_Company>>(); List<v_Company> list = comm.Result.ToList(); ViewData["haha"] = list; return View(); }
然后在前端页面调用
@{ ViewBag.Title = "Index"; var comm = ViewData["haha"] as List<MvcForAPI.Models.v_Company>; } @foreach (var item in comm) { <ul> <li>ID:@item.Id</li> <li>公司名称:@item.CompanyName</li> <li>公司领导:@item.CompanyLender</li> <li>公司编号:@item.CompanyCard</li> <li>公司邮箱:@item.CompanyEmail<li> </ul> }
-----------------------------------------------------------------------------------
下面是两个web,A调用B的Demo
B提供数据,负责A调用
B 的ashx public void ProcessRequest(HttpContext context) { //获取回调函数名 string callback = context.Request.QueryString["callback"]; IList<window> list = new List<window>(){new window() { userId = "duyixin", userName = "独一心", passWord = "阿斯顿", title = "这个是独一心的标题" },new window() { userId = "haha", userName = "淡出", passWord = "eneneg", title = "这个是哈哈的标题" },new window() { userId = "nan", userName = "电饭锅", passWord = "ddfd", title = "这个是NAN的标题" }}; JavaScriptSerializer JSSerializer = new JavaScriptSerializer(); string jsonp = JSSerializer.Serialize(list); context.Response.ContentType = "application/json"; //输出:回调函数名(json数据) context.Response.Write(callback + "(" + jsonp + ")"); }
A在前端获取
$.getJSON("http://localhost:15968/test.ashx?callback=?", function (data) { console.log(data) for (var i = 0; i < data.length; i++) { alert(data[i].userId + " is a " + data[i].userName + ‘且密码是:‘ + data[i].passWord + ‘标题是:‘ + data[i].title); } });
这样A就可以调用B中的数据进行操作了。
标签:
原文地址:http://www.cnblogs.com/ithuo/p/4775993.html