这一篇将使用Web Api和AJAX进行数据交互的记录,通过GET和POST请求。
本次使用的是VS2017+.NET CORE 2.1+AJAX
在实现本次测试之前,要先解决跨域问题和阐述一些概念。
跨域问题,在AJAX请求的时候无法访问,错误如下图。跨域问题具体的可以百度了解一下。
解决方案如下:
1.在ConfigureServices中添加服务
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddCors(options => { options.AddPolicy("stdio", p => p.AllowAnyOrigin()); }); }
2.在Configure中添加中间件。
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("stdio");//必须位于UseMVC之前 app.UseMvc(); }
这样就可以跨域访问了。
下面先对Get请求进行测试。
Get请求的实质是Url字符串的拼接。把传输的数据放在url地址中。
例如,上图中的数据就是放在url上。
1.Get请求基本类型 (参数的名字要匹配对应)
[Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase {[Route("Demo")]//这里我自己定义了路由 [HttpGet] public string Get(int id, string name) { return "这是尝试Get请求"; } }
$.ajax({ type: "Get", url: "http://localhost:12650/api/values/Demo", data: { id: 1, name: "Jim"}, success: function (res) { alert(res); }, error: function (msg) { alert(msg.responseText); } });
可以启动Web Api并打个断点进行查看。
可以看到AJAX传过来的值接收到了,这边返回一个字符串。
这样就完成了一次基本类型参数的请求。