C# Controller下的Action被Jquery Ajax跨域访问配置

17 篇文章 0 订阅

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);
    }
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值