.net core 允许跨域

允许所有跨域,在 startup.cs 中的 ConfigureServices 添加如下代码

services.AddCors(options =>
{
    options.AddPolicy("AllowAllCors",
        builder => builder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod());
});

在 startup.cs 中的  Configure 添加如下代码

app.UseCors("AllowAllCors")


允许指定跨域来源,在 startup.cs 中的 ConfigureServices 添加如下代码

services.AddCors(options =>
            {
                options.AddPolicy("AngularClientOrigin",
                    builder => builder.WithOrigins("https://localhost:44373")
                        .AllowAnyHeader()
                        .AllowAnyMethod());
            });

在 startup.cs 中的  Configure 添加如下代码

app.UseCors("AngularClientOrigin")

内容扩展:文件下载API

[Route("api/[controller]")]
[ApiController]
public class FileController : ControllerBase
{
    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="name">文件名</param>
    /// <returns></returns>
    [HttpGet]
    public IActionResult Down()
    {
        try
        {
            string path = AppDomain.CurrentDomain.BaseDirectory+ "file\\test.docx";
            var stream = System.IO.File.OpenRead(path);
            //application/msword word文件  application/octet-stream 为通用文件流
            //相关的可以参考HTTP Mime-Type对照表 : Content-Type(Mime-Type) 文件扩展名 http://www.jsons.cn/contenttype/
            return File(stream, "application/msword", Path.GetFileName(path));
        }
        catch (Exception ex)
        {
            return new JsonResult(ex.Message);
        }
    }
}

本文来自 www.luofenming.com