vue, axios, asp.net core, web api, 接收参数

本文介绍如何解决Vue前端应用通过Axios访问ASP.NET Core后端API的问题,包括配置跨域、设置请求头及使用代理服务等内容。

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

前端用 ant desgin vue 后端用asp.net core 3.1 中间用axios访问后台, 不管怎么着都访问不到
后来才搞明白.

废话少说. 直接上代码. 说点关键的部分.
vue这样写

<script>
import axios from 'axios';
var queryModel ={
	BoCiHao:'123456'
}
// 这个headers 可以不传, 默认就是 application/json
var headers =  {
        headers: { 
          'Content-Type': 'application/json',
        },
      }
      
axios.post('/api/FaHuoTongZhiDan/AjaxLoadData', this.queryModel, headers)
 .then(data => {
     alert('访问成功')
   })
 .catch(function (error) {
  console.log(error);
 });
   
</script>

后台,使用 [FromBody] 读取json参数


    [ApiController]
    [Produces("application/json")]
    [Route("api/[controller]/[action]")]
    public partial class FaHuoTongZhiDanController : ControllerBase
    {
		 [HttpPost]
		public string AjaxLoadData([FromBody]  ChaXunCanShuModel cxmodel )
		{
			// cxmodel.BoCiHao =="123456" 这里收到.的数值就是123456
		}
	}

在这里插入图片描述
传递的是json格式的数据
在这里插入图片描述
Startup.cs 文件,要允许跨域.

 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.AddDbContext<KWJL5.Models.kwjl5Context>();
             
            // services.AddElmah();
            //services.AddElmah<ElmahCore.XmlFileErrorLog>(options => {
            //    options.Path = "/error";
            //    options.CheckPermissionAction = context => context.User.Identity.IsAuthenticated;
            //    options.LogPath = "/errorlog";
            //    //options.FiltersConfig = "elmah.xml";
            //    //options.Filters.Add(new MyFilter());
            //    // options.Notifiers.Add(new ErrorMailNotifier("Email", emailOptions));
            //});

            //允许一个或多个来源可以跨域
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                    });
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        }

        // 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.UseHttpsRedirection();

            app.UseRouting();
            app.UseAuthorization();
            // app.UseCors("CustomCorsPolicy");
            app.UseCors("AllowAll"); // 允许跨域
            // app.UseElmah();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // app.UseHttpsRedirection();
            // app.UseMvc();
        }
    }

vue.config.js 中的配置, 在开发环境下要能正常访问到api的后台, 必须得这样配置代理服务.

module.exports = {
    devServer:{
        proxy:{
            '/api/':{
                target:"http://localhost:63558/",
                pathRewrite:{
                    '^/api/':"/api/"
                },
                logLevel:'debug',
                changeOrigin: true, 
                secure: false 
            }
        }
    },  
}
Vue 3.0 和 ASP.NET Core WebAPI 都支持动态路由,实现起来也比较简单。 首先,在 ASP.NET Core WebAPI 中,我们需要在 Startup.cs 中配置路由。可以使用以下代码: ``` app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action}/{id?}"); }); ``` 这个配置会将请求转发到对应的控制器和方法中。其中,{controller} 和 {action} 表示控制器和方法名,{id?} 表示可选参数。 接着,在 Vue 3.0 中,我们可以使用 vue-router 实现动态路由。可以使用以下代码: ``` const router = createRouter({ history: createWebHistory(), routes: [ { path: '/:controller/:action/:id?', name: 'dynamic', component: DynamicComponent } ] }) ``` 这个配置会将请求转发到 DynamicComponent 组件中。其中,:controller、:action 和 :id? 表示控制器、方法名和可选参数。 最后,我们可以在 DynamicComponent 组件中调用 ASP.NET Core WebAPI 中的动态路由。可以使用以下代码: ``` axios.get(`/api/${this.$route.params.controller}/${this.$route.params.action}/${this.$route.params.id}`) .then(response => { // 处理响应 }) .catch(error => { // 处理错误 }) ``` 这个代码会发送请求到对应的控制器和方法中,其中,this.$route.params.controller、this.$route.params.action 和 this.$route.params.id 分别对应控制器、方法名和参数。 以上就是 Vue 3.0 和 ASP.NET Core WebAPI 实现动态路由的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值