.net5 webapi跨域

文章展示了如何在ASP.NETCore应用程序中设置跨域策略,允许所有来源进行访问。首先,在Startup.cs的ConfigureServices方法中添加代码配置CORS策略,然后在Configure方法中启用该策略。此外,也在需要跨域的控制器上添加了[EnableCors]特性,确保控制器支持跨域请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在Startup.cs中ConfigureServices方法下添加以下代码

// 配置跨域处理,允许所有来源

            services.AddCors(options => {

                // this defines a CORS policy called "default"

                options.AddPolicy("default", policy => {

                    policy.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();

                });
            });

2.在Startup.cs中Configure方法下添加以下代码

app.UseCors("default");//跨域

3.在需要跨域的控制器添加

using Microsoft.AspNetCore.Cors;
[EnableCors("default")]//跨越

Stratup.cs总体代码

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.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApi
{
    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.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi", Version = "v1" });
            });

            // 配置跨域处理,允许所有来源

            services.AddCors(options => {

                // this defines a CORS policy called "default"

                options.AddPolicy("default", policy => {

                    policy.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();

                });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseAuthorization();
            app.UseCors("default");//跨域
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

需要跨域的控制器代码

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using WebApi.Dal;
using WebApi.Models;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("default")]//跨越
    public class PatientInformationController : ControllerBase
    {
        Sqlhelper Sqlhelper = new Sqlhelper();
        [HttpGet]
        public List<book> Get() {
            string sql = "select * from dbo.book";
            DataTable a = Sqlhelper.FindAutoInfo(sql);
            List<book> book = ToModelList(a);
            return book; 
        }
        private List<book> ToModelList(DataTable table)
        {
            List<book> book = new List<book>();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow row = table.Rows[i];
                book booke = ToModel(row);
                book.Add(booke);
            }
            return book;
        }
        private book ToModel(DataRow row)
        {
            book book = new book();
            book.bookid = (int)Sqlhelper.FromDbValue(row["bookid"]);
            book.bookname = Sqlhelper.FromDbValue(row["bookname"]).ToString();
            book.bookauthor = Sqlhelper.FromDbValue(row["bookauthor"]).ToString();
            book.booktype = Sqlhelper.FromDbValue(row["booktype"]).ToString();
            book.bookpress = Sqlhelper.FromDbValue(row["bookpress"]).ToString();
            book.bookprice = Sqlhelper.FromDbValue(row["bookprice"]).ToString();
            book.bookstock = (int)Sqlhelper.FromDbValue(row["bookstock"]);
            book.bookstatus = (int)Sqlhelper.FromDbValue(row["bookstatus"]);
            return book;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值