ASP.NET Core 启用跨域请求 (CORS)

ASP.NET MVC 配置允许跨域访问

1、管理 NuGet 添加引用
      Microsoft.AspNetCore.Cors

2、Startup.cs【使用命名的策略和中间件的 CORS,CORS 中间件处理跨域请求】

public void ConfigureServices(IServiceCollection services)
{
    #region 跨域

    var urls = Configuration["AppSetting:Cores"].Split(',');

    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder =>
            {
                //builder.WithOrigins("https://localhost:44390", "http://0.0.0.0:3201").AllowAnyHeader();
                builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials();
            });
    });

    #endregion

    services.AddMvcCore()
       .AddAuthorization()
       .AddJsonFormatters();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseAuthentication();
    app.UseHttpsRedirection();

    #region 跨域
    app.UseCors("AllowSpecificOrigin");
    #endregion

    app.UseMvc();
}

3、appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AppSetting": {
    "Cores": "https://localhost:44390,http://0.0.0.0:3201"
  },
  "AllowedHosts": "*"
}

4、Controller【使用属性启用 CORS,[EnableCors] 属性提供了一种全局应用 CORS 的替代方法】

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

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

        // GET api/Default/alias
        [HttpGet("{alias}")]
        public Author Get(string alias)
        {
            return new Author { Id = 1, Name = alias, Age = 20 };
        }

        // GET api/Default/GetAuthor?id=100&alias=abc
        [HttpGet("GetAuthor")]
        public Author GetAuthor(int id, string alias)
        {
            return new Author { Id = id, Name = alias, Age = 20 };
        }

        // GET: api/Default/search?namelike=th
        [HttpGet("Search")]
        public IActionResult Search(string namelike)
        {
            var result = "result:" + namelike;
            if (!result.Any())
            {
                return NotFound(namelike);
            }
            return Ok(result);
        }

        // GET api/Default/about
        [HttpGet("About")]
        public ContentResult About()
        {
            return Content("An API listing authors of docs.asp.net.");
        }

        // GET api/Default/version
        [HttpGet("version")]
        public string Version()
        {
            return "Version 1.0.0";
        }

        // POST: api/Default
        [HttpPost]
        public void Post([FromBody] string value)
        {
            string dt = DateTime.Now.ToShortDateString();
        }

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

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

    public class Author
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }
    }
}

5、

6、
 

你可能感兴趣的:(.NET,Core)