WebApi 動態參數 dynamic 使用

在調用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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章