首页 > 其他分享 >WebApi 动态参数 dynamic 使用

WebApi 动态参数 dynamic 使用

时间:2023-07-22 11:33:34浏览次数:51  
标签:WebApi function stringify dynamic System JSON 参数 using config

在调用WebAPI时,调用方法主要有get和post,但参数传递需要注意几点,下面简单介绍一下ajax 调用时传参的几种方法:

  • webapi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace PostDemo.Controllers
{
    [EnableCors(origins:"*",headers:"*",methods:"*")]  //处理跨域访问
    public class HomeController : ApiController
    {
        [HttpGet]
        public string Get() {
            return "Hello,This is Test!";
        }
        [HttpGet]
        public string Get(string name) {
            return $"This is parameter:{name} is input";
        }
        [HttpPost]
        public JObject PostInfo(dynamic obj) {  //动态类型类似于推断类型,客户端调用时需传入json格式字符串
            //如data:JSON.stringify(obj),同时需要指定类型 contentType=application/json 
            string s1 = obj.name;
            string s2 = obj.age;
            return JObject.Parse("{\"name\":\"" + s1 + "\",\"age\":" + s2 + "}");
        }
    }
}

  • 服务端解决跨域问题
  1. 安装 Micrsoft.AspNetWebApiCors
    image

2.开启跨域配置

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using System.Web.Http.Cors;
namespace PostDemo
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            config.EnableCors();
            // Web API 路由
            config.MapHttpAttributeRoutes();
            config.Formatters.Clear(); //清除默认格式 xml
            config.Formatters.Remove(config.Formatters.XmlFormatter); //删除xml格式
            config.Formatters.Add(new JsonMediaTypeFormatter()); //增加JSON格式
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

  • html
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery-1.10.2.js"></script>
		<script>
		
			function f1(){
				$.ajax({
					type:"get",
					url:"http://localhost:58208/api/home",
					data:{},
					async:true,
					success:function(res){
						$("#txt").text(JSON.stringify(res));
						
					},
					error:function(err){
						alert(JSON.stringify(err));
					}
					
				});
				
			}
			
           function f2(){
           	$.ajax({
           		type:"get",
           		url:"http://localhost:58208/api/home",
           		data:{"name":"张三"},
           		async:true,
           		success:function(res){
           			$("#txt").text(JSON.stringify(res));
           			
           		},
           		error:function(err){
           			alert(JSON.stringify(err));
           			
           		}
           	});

           }
		function f3() {
		
			$.ajax({
				type:"post",
				url:"http://localhost:58208/api/home",
				contentType:"application/json",
				data:JSON.stringify({"name":"张三","age":12}),
				async:true,
				success:function(res){
					$("#txt").text(JSON.stringify(res));
				},
				error:function(err){
					alert(JSON.stringify(err));
					
				}
			});
		
			
		}
		</script>
	</head>
	<body>
		<div>
			<button onclick="f1()">测试1-Get无参</button>
			<button onclick="f2()">测试2-Get有参</button>
			<button onclick="f3()">测试3-Post动态参数</button>
		</div>
		<div>
			<textarea id="txt" rows="25" cols="38" ></textarea>
		</div>
	</body>
</html>

  • 效果
    image

标签:WebApi,function,stringify,dynamic,System,JSON,参数,using,config
From: https://www.cnblogs.com/sundh1981/p/17573074.html

相关文章

  • m基于扩频解扩+LDPC编译码的通信链路matlab误码率仿真,调制对比QPSK,16QAM,64QAM,扩频
    1.算法仿真效果matlab2022a仿真结果如下:     2.算法涉及理论知识概要      在现代通信系统中,扩频技术被广泛应用于数字通信链路中。扩频技术通过将要传输的信息序列与一个宽带的伪随机码序列进行卷积,将原始信号转换成一个具有更大带宽的扩频信号。在接收端......
  • 实现PS端YOLO网络参数导入函数
    实现PS端YOLO网络参数导入函数目的:从SD卡读取Python生成的YOLO网络的所有参数的bin文件,并存储到DDR3内存中,为YOLO网络的推理和计算功能做准备在main.c文件中调用load_param函数,一次性导入所有层的参数前提:已经在Vivado和Vitis中创建了工程,并导出了硬件平台已经在Pyth......
  • java aop记录用户操作日志如何获取请求参数
    在Java中,AOP(面向切面编程)是一种编程范式,它可以将横切关注点(如日志记录)从业务逻辑中分离出来,使得代码更加清晰、可维护和可扩展。在记录用户操作日志时,我们可以使用AOP来拦截请求并获取请求参数。首先,我们需要创建一个切面类来实现日志记录的逻辑。假设我们使用Spring框架和AspectJ......
  • url中的参数带有&连接符号处理
     keyword:url参数 连接符  %26代替&,  %3F代替?   接受页面不需要改动任何, &的asc码为%26. ?的asc码为%3F. 如:toUrlProject.action?url=nonTopicDetailPlanTask.action%3FprojectInfo.id='+@moduleId+'%26menuId=26......
  • 链接参数export dynamic和-rdynamic的使用
    存在程序main通过dlopen使用libA中的符号:main.c:1#include<stdio.h> 2#include<dlfcn.h> 3  4typedefvoid(*func)(void);  5  6  7voidtest_main() 8{ 9  return;10}11 12 13intmain()14{15  void*handle=dlopen("./libA.so",RTLD_N......
  • 使用参数属性对.Net WebApi参数校验
    .NetWebApi进行优雅的参数校验受到了springboot中注解校验参数的启发,于是想,难道微(巨)软(硬)的.net不行吗?于是有了本次尝试。当我们日常开发webapi接口时,难免会有一堆参数校验,例如校验参数是否为空,密码长度……条件校验一般的操作是下面这样的:emm……目前这是2个字段参......
  • pytest 参数化
    [email protected]('a,b,sum',[#参数化出来3组数据(1,2,3),(2,3,5),(3,-19,-16)])deftest_add(a,b,sum):asserta+b==sum#如果名称等于main输出pytest.main([文档,sv参数])if__name__=='__main__':pytest.main([__......
  • 线性模型(linear model)基本定义及参数求解数学本质、损失函数的选择与评估数学原理、及
    线性模型(linearmodel)基本定义及参数求解数学本质、损失函数的选择与评估数学原理、及其基于线性模型衍生的其他机器学习模型相关原理讨论1.线性模型简介0x1:线性模型的现实意义在一个理想的连续世界中,任何非线性的东西都可以被线性的东西来拟合(参考Taylor......
  • 踩坑记录,axios post方法请求参数出现在地址栏的问题
    某天使用axios做post请求接口突然不好使了,总是调不通,并且参数都是出现在访问地址后,如图: 找了半天,原来是调用api的时候,参数使用错误:由于post 请求接收params参数和data参数,这里是cv上面get请求的方法,只修改method为post,下面的params忘记改成data了!,导致axios拿到params后直接......
  • .net core webapi 局域网内机器可以互相访问
    1、  使用localhost的方式运行程序  dotnetFitnessequipment.dll--urls=http://localhost:5038    是无法通过ip访问的,只可以使用localhost访问    2、以ip方式运行程序,dotnetFitnessequipment.dll--urls=http://192.168.3.213:5038     ......