MVC controller中的跨域访问

知道WEBAPI的跨域访问解决方法,但是好像没有MVC下的方法,在网上搜了很多方法,感觉太麻烦,最后发现只要在后台访问就完美解决跨域问题。

JS调用方法,把需要跨域访问的网址放在后台,则不会提示跨域访问问题。



KanBanController.cs

 
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace KanBan.Controllers
{
    public class KanBanController : BaseController
    {
        // GET: KanBan
        public ActionResult Index()
        {
            return View();
        }
 
        public JsonResult GetKanBanData1()
        { 
            string url = "http://10.10.27.29/openapi/service/pms/record/getVehicleRecords?appkey=61fdb13b&time=1479364577369";
            string html = DBKanBan.GetHtml(url); 
 

            string js = JsonConvert.SerializeObject(html);

            return Json(js);
        }
   }
}


DBKanBan.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; 
using System.Data.Sql;
using System.Data;
using Newtonsoft.Json;
using System.Drawing.Imaging;
using System.Drawing; 
using System.Data.SqlClient; 
using System.Net;
using System.IO;
using System.Text;

namespace KanBan.DAL
{
    public static class DBKanBan
    { 

        public static string GetHtml(string URL)
        {
            // HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
            
            WebRequest wrt;
            wrt = WebRequest.Create(URL);
            wrt.Credentials = CredentialCache.DefaultCredentials;

            string code = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "admin", "123"))); //此处是用户名和密码

            //添加Authorization到HTTP头
            wrt.Headers.Add("Authorization", "Basic " + code);
            wrt.Method = "POST";
            WebResponse wrp;
            
            wrp = wrt.GetResponse();
            //wrp.Headers.Add("Access-Control-Allow-Origin", "*");
            string reader = new StreamReader(wrp.GetResponseStream()).ReadToEnd();
           // string reader = new StreamReader(wrp.GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();
            try
            {
                wrt.GetResponse().Close();
            }
            catch (WebException ex)
            {
                throw ex;
            }
            return reader;
        }

  
 
    }
}

 

你可能感兴趣的:(C#,MVC4,WEB前端)