.net core api Cors跨域 ajax调用 (非JSONP) & post 传参数 不为 NULL

一、让.net core api 支持跨域访问

①修改 Startup.cs 文件:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace KLKY_API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //2021-3-10 09:58:41 添加以下代码:
            //定义配置跨域处理,见: https://www.cnblogs.com/tianma3798/p/14254758.html
            services.AddCors(options =>
            {
                //完全公开,不支持cookie传递
                options.AddPolicy("any", policy =>
                {
                    policy.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                });

                //指定域名公开,可以支持cookie
                options.AddPolicy("all", policy =>
                {
                    policy.WithOrigins(
                        "null", //file:///本地测试可以访问
                        "http://localhost:7294",
                        "http://localhost:8081"
                        )
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "area",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
            app.UseCors();//开启 跨域处理 2021-3-10 10:03:54   
        }
    }
}

②控制器Controller 添加属性 [EnableCors("any")] (或[EnableCors("all")],详细见上文Startup.cs 文件的ConfigureServices函数里的 AddCors,需要哪一种就指定哪一种...):

using KLKY_API.Common.ApiResult;
using KLKY_BLL.User;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using static KLKY_API.Common.ApiResult.ApiBaseResultEnum;

namespace KLKY_API.Areas.User.Controllers
{
    [EnableCors("any")]//指定跨域公开
    [ApiController]//说明本Controller是Api的Controller
    [Area("User")]//说明本Controller的区域名称叫User
    [Route("API/[area]/[controller]/[action]")]//说明本Controller的访问url是:api/区域名称/控制器名称/函数名称
    public class LoginController : BaseApiController
    {
        #region 用户登录   
        [HttpPost]
        //https://localhost:44302/api/User/Login/UserLogin2
        public ApiBaseResult UserLoginPost([FromForm] NamePassword namePwd)
        {
            if (namePwd == null)
            {
                return ReturnApiDefaultResult(false, ((int)ErrorCode.Arguments).ToString(), ErrorCode.Arguments.GetRemark(), null);          
            }
            else
            {   
                DataTable dt = LoginBLL.UserLogin(namePwd.Name, namePwd.Password);
                if (dt != null && dt.Rows.Count > 0)
                {
                    return ReturnApiBaseResult(dt);//返回登录用户数据
                }
                else
                {
                    return ReturnApiNullResult();//无数据
                }
            }
        }
        public class NamePassword
        {
            public string Name { get; set; }
            public string Password { get; set; }
        }
        #endregion
    }
}

注:修改了 Startup.cs 文件,并且Controller控制器开启[EnableCors("any")] 跨域公开之后,就不用Jsonp来跨域访问了,ajax跨域调用的写法就和本地调用一样了....

二、POST跨域AJAX调用,传参数不为NULL

<html>
<head>
    <title>登录</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
    账号:<input type="text" id="txtName" value="admin" /><br />
    密码:<input type="text" id="txtPwd" value="admin" /><br />
    <input type="button" id="btnSubmit" value="登录" />
    <script>
        $(function () {
            $("#btnSubmit").click(function () {
                var name = $("#txtName").val();
                var pwd = $("#txtPwd").val();
                var param = { "Name": name, "Password": pwd };
                $.ajax({                   
                    type: "POST",
                    url: "https://localhost:44302/api/User/Login/UserLoginPost",
                    data: param,
                    dataType: "json",
                    //contentType: "application/json",
                    success: function (req) {
                        if (req.result == "Success") {
                            alert("登录成功!");
                        }
                        else {
                            alert(req.messages + "[" + req.errors + "]");
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>

DEMO页面地址是:http://localhost:7294/login.html

API接口地址是:https://localhost:44302/api/User/Login/UserLoginPost

端口号完全不一样,是典型的跨域调用AJAX...

POST的传递的参数名称,必须和API那头的参数类的属性名称要一样并且API那边参数 要添加 [FromForm]  (注意,不是[FromBody] !),就能获取到POST过来的参数了!

三、POST跨域AJAX调用API接口效果如下:

 在线测试:https://tester.hamm.cn/

四、GET方式(Cors)跨域调用API

①Demo页面 (http://localhost:2551/login_post.html

<html>
<head>
    <title>登录Get</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
    账号:<input type="text" id="txtName" value="admin" /><br />
    密码:<input type="text" id="txtPwd" value="admin" /><br />
    <input type="button" id="btnSubmit" value="登录" />
    <script>
        $(function () {
            $("#btnSubmit").click(function () {
                var name = $("#txtName").val();
                var pwd = $("#txtPwd").val();
                $.ajax({
                    type: "GET",
                    url: "https://localhost:44302/api/User/Login/UserLoginGet",
                    data: { Name: name, Password: pwd },
                    success: function (req) {
                        if (req.result == "Success") {
                            alert("登录成功!");
                        }
                        else {
                            alert(req.messages + "[" + req.errors + "]");
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>

②API的Controller (https://localhost:44302/api/User/Login/UserLoginPost

using KLKY_API.Common.ApiResult;
using KLKY_BLL.User;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using static KLKY_API.Common.ApiResult.ApiBaseResultEnum;

namespace KLKY_API.Areas.User.Controllers
{
    [EnableCors("any")]//指定跨域公开
    [ApiController]//说明本Controller是Api的Controller
    [Area("User")]//说明本Controller的区域名称叫User
    [Route("API/[area]/[controller]/[action]")]//说明本Controller的访问url是:api/区域名称/控制器名称/函数名称
    public class LoginController : BaseApiController
    {  
        [HttpGet]
        //https://localhost:44302/api/User/Login/UserLoginGet?Name=admin&Password=admin    
        public ApiBaseResult UserLoginGet(string Name, string Password)
        {
            if (string.IsNullOrWhiteSpace(Name) || string.IsNullOrWhiteSpace(Password))
            {
                return ReturnApiDefaultResult(false, ((int)ErrorCode.Arguments).ToString(), ErrorCode.Arguments.GetRemark(), null);
            }
            else
            {
                DataTable dt = LoginBLL.UserLogin(Name, Password);
                if (dt != null && dt.Rows.Count > 0)
                {
                    return ReturnApiBaseResult(dt);//返回登录用户数据
                }
                else
                {
                    return ReturnApiNullResult();//无数据
                }
            }
        }   
    }
}

③返回值

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值