最近公司項目遇到了這個問題,分享一下。
javaScript進行跨域訪問時需要服務器許可,不是任何域都接受跨域請求的。
這裡我遇到的問題是服務端有返回數據,但是客戶端無法取得響應數據。
解決方案1.在web.config加入已下請求頭:
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with"/>
<add name="Access-Control-Allow-Origin" value="*" />
解決方案2.程序初始化是加入請求頭
public MvcApplication()
{
this.BeginRequest += new EventHandler(MvcApplication_BeginRequest);
}
void MvcApplication_BeginRequest(object sender, EventArgs e)
{
Response.AddHeader("Access-Control-Allow-Methods", "OPTIONS,POST,GET");
Response.AddHeader("Access-Control-Allow-Headers", "x-requested-with");
Response.AddHeader("Access-Control-Allow-Origin", "*");
}
Access-Control-Allow-Origin:* ,這就表示允許跨域訪問,所以可以正常訪問該域,而對於其他沒有該標識的域就會出現禁止訪問提示。值可以是 URL 或 *,如果是 URL 則只會允許來自該 URL 的請求,* 則允許任何域的請求;
服務端的接口代碼
public JsonResult NormalUpload()
{
HttpContext context = this.HttpContext.ApplicationInstance.Context;
String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);
String savePath = "/uploadfiles/images/";
String saveUrl = "/uploadfiles/images/";
Hashtable extTable = new Hashtable();
extTable.Add("image", "gif,jpg,jpeg,png,bmp");
int maxSize = 1000000;
string result = "0";
HttpPostedFile imgFile = context.Request.Files["imgFile"];
if (imgFile == null)
{
result = "請選擇文件。";
}
String dirPath = context.Server.MapPath(savePath);
if (!Directory.Exists(dirPath))
{
result = "上傳目錄不存在。";
}
String fileName = imgFile.FileName;
String fileExt = Path.GetExtension(fileName).ToLower();
if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
{
result = "上傳文件大小超過限制。";
}
if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable["image"]).Split(','), fileExt.Substring(1).ToLower()) == -1)
{
result = "上傳文件擴展名是不允許的擴展名。\n只允許" + ((String)extTable["image"]) + "格式。";
}
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
String filePath = dirPath + newFileName;
imgFile.SaveAs(filePath);
String fileUrl = saveUrl + newFileName;
Hashtable hash = new Hashtable();
hash["error"] = result;
hash["url"] = fileUrl;
return Json(hash, JsonRequestBehavior.AllowGet);
}