前端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)
{
}
}
}