jquery ajax 跨域访问.net core Api

前端ajax

前端想要跨域访问后台,首先想到的可能是jsonp 的传输格式,但是这样造成的问题是很多时候无法做到异步的效果。

所以只需要在基础ajax json数据格式传输上设置允许跨域策略即可。

添加内容如下:

xhrFields: {
                    withcredentials: true //允许跨域策略
                }

即可。

直接上代码:
  

          $.ajax({
                type: "POST", //提交方式
                dataType: "json", //返回数据格式为json
                url: URL, //模拟web服务,提交到方法
                async: true, //异步传输
                xhrFields: {
                    withcredentials: true //允许跨域策略
                },
                contentType: "application/json;charset=utf-8", //body方式提交参数
                data: JSON.stringify(parameters), //后台参数加上FromBody
                //contentType: "application/x-www-form-urlencoded",//form方式提交参数
                //data:parameters,//后台参数加上FromForm
                timeout: 10000, //允许最长等待时间,这设置为十秒
                beforeSend: function() {
                    //do something.    
                    //打开loading    

                },
                complete: function(xhr, status) {
                    //do something.    
                    //关闭loading    

                },
                success: function(result, status, xhr) {
                    //成功回调函数
                        SuccessCallback(result);

                },
                error: function(xhr, textStatus, errorThrown) {
                  //do error thing

                }
            });

后台.net core 

  • Step1

修改Startup.cs 类,在这个类里面设置允许跨域访问,并且设置允许的域名。

话多疲累,还是直接上代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace PTS_backstage
{
    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_2);

            //添加cors跨域站点
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                builder =>
                {

                    builder.WithOrigins("http://example.com",
                                        "http://127.0.0.1:80")
                                        .AllowAnyHeader()
                                        .AllowAnyMethod()
                                        ;
                });
            });


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //将 CORS 策略应用到所有应用终结点:
            app.UseCors();

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}
  • Step2

    添加.net core 跨域方法。

1.新建一个core api 类 。

2.在方法上添加允许跨域访问特性。

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace PTS_backstage.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DefaultController : ControllerBase
    {
        // GET: api/Default
        [EnableCors]        // Default policy.
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Default/5
        [EnableCors]        // Default policy.
        [HttpGet("{id}", Name = "Get")]
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Default
        [EnableCors]        // Default policy.
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT: api/Default/5
        [EnableCors]        // Default policy.
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE: api/ApiWithActions/5
        [EnableCors]        // Default policy.
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值