前端Ajax,后端.NET C# ASP.NET WebApi配置跨域访问

1.前端写法

    <script src="jquery-1.10.2.js"></script>
    <script>
        function Set() {
            $.ajax({
                url: "http://192.168.0.29:57461/api/User/LoginUser",
                dataType: "json",

/*ajax跨域参数配置 开始*/
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,

/*ajax跨域参数配置 结束*/
                data: { Level: "district",
                    Company_Id: "xxxx",
                    User_Id: "xxxx"
                },
                type: "post",
                success: function (data) {
                    console.log(data);
                    alert('成功')
                },
                error: function (data) {
                    alert('失败')
                    console.log(data);
                }
            });
        }
    </script>

2.后端配置

API项目下Web.config文件内,在system.webServer节点下补充以下内容:

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Credentials" value="true" />
        <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>

 

3.后端api写法,与正常api写法一样,不需要调整

/// <summary>
    /// 角色权限类接口
    /// </summary>
    public class UserController : ApiController
    {
        public UserController() { }

        [HttpPost]
        public IHttpActionResult LoginUser([FromBody] BaseUserModel model)
        {
            //xxxxx业务代码
            return Ok(new Response<Object>() {Data=true});
        }

    }

public class BaseUserModel : BaseInputModel
    {

    }

 

public class BaseInputModel
    {
        /// <summary>
        /// 级别
        /// </summary>
        public string Level { get; set; }    

        /// <summary>
        /// 项目平台Id
        /// </summary>
        public string Company_Id { get; set; }


        /// <summary>
        /// 创建人Id
        /// </summary>
        public string User_Id { get; set; }
    }

4.注意:以上实例ajax调用API的路径,需要WebApi项目调整WebApiConfig.cs文件,如下:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
             // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",//补充{action}
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

posted @ 2021-04-24 11:09  jeff151013  阅读(237)  评论(0编辑  收藏  举报