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

前端用 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 
            }
        }
    },  
}

猜你喜欢

转载自blog.csdn.net/phker/article/details/110927775