asp net core mvc 跨域ajax解决方案

本文介绍了在服务端配置CORS策略的方法,通过在Startup文件中设置允许的源,并在API控制器启用CORS,确保jQuery和axios的跨域请求能携带Cookie。示例代码展示了如何使用jQuery和axios进行跨域GET请求。

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

1、配置服务端

Startup文件中配置Cors策略:

IEnumerable<Client> clients= Configuration.GetSection("Clients").Get(typeof(IEnumerable<Client>)) as IEnumerable<Client>;

            List<string> urls = new List<string>();
            foreach (var client in clients)
            {
                urls.AddRange(client.AllowedCorsOrigins);
            }
            services.AddCors(options =>
            {
                options.AddPolicy("default",
                    builder => builder.WithOrigins(urls.ToArray())
                                    .AllowAnyHeader()
                                    .AllowCredentials()
                                    .AllowAnyMethod());
            });

启用CORS策略,可以在Startup文件中配置,也可以在具体的ApiController中配置,代码分别如下:

 app.UseCors("default");
[Authorize]
[EnableCors("default")]
public class NavigationMenuController:Controller
{
    private NavigationMenuService navigationMenuService;

    public NavigationMenuController(NavigationMenuService navigationMenuService)
    {
        this.navigationMenuService = navigationMenuService;
    }
}

2、JQuery请求

$.ajax({
    url: 'http://localhost:5000/api/Private/Values/Identity',
    type: 'GET',
    dataType: 'json',
    crossDomain: true,
    xhrFields: {
        withCredentials: true
    },
    success: function (result) {
        $('#platformResult').val(JSON.stringify(result));
    }
});

红字是关键 ,值得注意的是需要配置 withCredentials,否则请求不会带上Cookie

3、 axios请求

  axios({
    url:
    config.authority +
    "/api/xxxxxxxxxx?clientId=" +
    escape(config.client_id),
    method: "GET",
    withCredentials: true
  }).then(function (result) {
    if (result.success == undefined) {
      self.menuItems = result || [];
    }
  });
### ASP.NET MVC 项目示例教程 #### 创建一个新的ASP.NET MVC应用程序 要创建新的ASP.NET MVC应用,可以使用Visual Studio IDE。通过模板向导选择MVC选项来初始化项目结构[^3]。 ```csharp public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } ``` 此代码片段展示了`Startup.cs`文件中的基本配置方法,用于设置中间件管道和服务集合[^2]。 #### 数据库集成与操作 对于数据库交互,在ASP.NET Core MVC环境中通常采用Entity Framework Core作为ORM工具。定义模型类并利用DbContext来进行CRUD操作[^1]。 ```csharp using Microsoft.EntityFrameworkCore; public class ApplicationDbContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("YourConnectionStringHere"); } } public class Product { public int Id { get; set; } public string Name { get; set; } // Other properties... } ``` 上述例子说明了怎样建立一个简单的数据上下文以及实体对象以连接SQL Server数据库。 #### 资源共享(CORS) 配置 当构建前后端分离的应用程序时,可能遇到浏览器同源策略限制的问题。可以通过调整CORS策略允许特定名下的请求访问API资源。 ```csharp services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, builder => { builder.WithOrigins("http://example.com") .AllowAnyHeader() .AllowAnyMethod(); }); }); // In the configure method of startup file add this line before UseMvc or UseEndpoints. app.UseCors(MyAllowSpecificOrigins); ``` 这段代码实现了自定义的政策,使得来自指定前端服务器的AJAX调用能够成功到达后端服务。 #### 处理常见错误及解决方案 - **视图找不到**: 确认控制器返回View()的结果指向正确的路径;检查命名空间是否匹配。 - **表单提交失败**: 使用Fiddler或其他调试工具查看POST请求的有效载荷和响应状态码;验证Model State有效性。 - **Session丢失问题**: 设置适当会话超时时间,并考虑启用持久化存储机制如Redis缓存。 这些提示可以帮助开发者快速定位并修复日常开发过程中可能出现的一些典型难题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值