.net core webapi 跨域问题

首先在startup.cs中加入 

       services.AddCors(m => m.AddPolicy(Any, a => a.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()));

       app.UseCors(Any);

        public void ConfigureServices(IServiceCollection services)
        { 
            services.AddControllers();

            services.AddCors(m => m.AddPolicy(Any, a => a.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()));
 
        }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
           // app.UseMvc();
            app.UseRouting();
            //允许跨域 位置和必须放对,否则加载出错
            app.UseCors(Any);
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
 
        }

  在controller中加入    [EnableCors("Any")]  好像不加也可以用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WLCloudAPI.Models;
using WLCloudAPI.Repositories;
using WLCloudAPI.util;

namespace WLCloudAPI.Controllers
{
    [ApiController]
    [EnableCors("Any")]
    [Route("api/[controller]")]
    public class testController : Controller
    {
        private readonly ITestRepository _testRepository; 
        public testController(ITestRepository testRepository)
        {
            _testRepository = testRepository;
        }

        [HttpGet]
        public async Task> Get1()
        {
          return await _testRepository.GetTest();

        }

    }
 
}

 

你可能感兴趣的:(WEBAPI,WEB前端,asp.net,core)