1)修改Web.Config
在节点<system.webServer>添加跨域配置
<!--允许跨域 开始-->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<!--允许跨域 结束-->
2)添加允许访问基类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LintwaySales
{
/// <summary>
/// 指定站点允许跨域访问(基础类)
/// </summary>
public class AllowOriginAttribute
{
public static void onExcute(ControllerContext context, string[] AllowSites)
{
var origin = context.HttpContext.Request.Headers["Origin"];
Action action = () =>
{
context.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
};
if (AllowSites != null && AllowSites.Any())
{
if (AllowSites.Contains(origin))
{
action();
}
}
}
}
public class ActionAllowOriginAttribute : ActionFilterAttribute
{
public string[] AllowSites { get; set; }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
AllowOriginAttribute.onExcute(filterContext, AllowSites);
base.OnActionExecuting(filterContext);
}
}
public class ControllerAllowOriginAttribute : AuthorizeAttribute
{
public string[] AllowSites { get; set; }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
AllowOriginAttribute.onExcute(filterContext, AllowSites);
}
}
}
3)修改Action方法
/// <summary>
/// 根据批次主键获取批次
/// </summary>
/// <param name="BatchID"></param>
/// <returns></returns>
/// 指定Action允许跨域访问
[HttpPost]
[ActionAllowOrigin(AllowSites = new string[] { "*" })]
public ActionResult GetBatch(string BatchID)
{
string exceptionAction = MethodBase.GetCurrentMethod().ReflectedType.Name + "." + MethodBase.GetCurrentMethod().Name; //获取命名空间 + 类名 + 方法名
try
{
var data = _BatchServer.GetBatch(BatchID);
return Json(new { code = MyEnum.ResponseStatus.Success, data = data, msg = "" }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
string Remark = ((int)MyEnum.LogType.ErrorLog).ToString();
_ExceptionLogServer.AddLog(ex.ToString(), exceptionAction, System.Guid.Empty, Remark);
return Json(new { code = MyEnum.ResponseStatus.Fail, data = "", msg = ex.ToString() }, JsonRequestBehavior.AllowGet);
}
}
4)Jquery Ajax调用Action
$.ajax({
type: "POST",
dataType: "json",
url: base.ServerBaseUrl + 'Batch/GetBatch',
data: {
BatchID: BatchID
},
success: function (result) {
if (result.code == base.ResponseSuccess) {
var data = result.data;
} else {
mui.alert(base.QRCodeError, base.alertMsg);
}
},
error: function () {
mui.alert(base.GetDataFail, base.alertMsg);
},
complete: function () {
layer.close(index);
}
});