网上这方面很大,别人怎么写我照着写,ok 记下来以后增加记忆
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("DomainKYHttp",
builder => builder.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
.AllowCredentials()));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
}
app.UseCors("DomainKYHttp");
app.UseHttpsRedirection();
app.UseMvc();
}
#region 跨域 指定特定的请求路径
var urls = Configuration["AppConfig:Cores"].Split(',');
services.AddCors(options =>
options.AddPolicy("AllowSameDomain",
builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials())
);
#endregion
[HttpGet("{id}/{name}")]
public async Task<JsonResult> Get(int id, string name)
{
return new JsonResult(await Task.Run(()=>id+" "+name));
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]dynamic user)
{
return new ObjectResult(await Task.Run(() => user));
}
// PUT: api/GetMvc/5
[HttpPut("{id}")]
public async Task<JsonResult> Put(int id, [FromBody]string value)
{
return new JsonResult(await Task.Run(() => id + JsonConvert.SerializeObject(value)));
}
//[HttpPut("{id}")]
//public JsonResult Put(int id, [FromBody] string value)
//{
// return new JsonResult(value);
//}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public async Task Delete(int id)
{
await Task.Run(() => id);
}
//[HttpDelete("{id}")]
//public void Delete(int id)
//{
//}
前端
$.get("https://localhost:44352/api/GetMvc/145/ewfaf", function (data) {
alert(data);
});
//
//跨域
post
$.ajax({
url: "https://localhost:44352/api/GetMvc",
type: "POST",
contentType: "application/json; charset=utf-8", //跨域
data: '{ "UserID": 1, "UserName": "test", "UserEmail": "test@cnblogs.com" }',
dataType: 'json',
success: function (data) {
debugger;
alert(JSON.stringify(data));
}
});
//put
$.ajax({
url: "https://localhost:44352/api/GetMvc/123",
type: "put",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify("Jeffcky"),
success: function (data) {
alert(data);
}
});
$.ajax({
url: "https://localhost:44352/api/GetMvc/123",
type: "Delete",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {}
})