webapi 对象传值


前言

webapi 传值和mvc略有不同,一不小心容易出错,简单总结webapi传值。

按照mvc方式传值会出错415

1、mvc传值

function mvcPassValue() {
        var user = { Age: 6, Username: "hurne", remark: "hehe" }
        var muenmodel = { id: 3, url: "url", User: JSON.stringify(user) };
        var Testclass = {
             id : 1,
             name : "datong",
             muen : muenmodel
        };

         $.ajax({
            type: "post",
             url: "@Url.Action("testentity")",
             data: Testclass,
            success: function () {
                alert(0);
            }
        });

    }
前段代码
//action 
[HttpPost]
        public JsonResult testentity(Testclass model)
        {
            var userInfo = JsonConvert.DeserializeObject<userinfo>(model.Muen.user);
            return Json(new { data = model });
        }

//实体类

 public class Testclass
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public muen Muen { get; set; }
    }

    public class muen
    {
        public int Id { get; set; }

        public string url { get; set; }

        public string user { get; set; }
    }

    public class userinfo
    {
        public int age { get; set; }

        public string userName { get; set; }

        public string Remark { get; set; }
    }
action

后台正常接收

2、webapi 传值

 前段代码:修改为对应的webapi后台地址 

[HttpPost, Route("testentity")]
        public object testentity(Testclass model)
        {
            var userInfo = JsonConvert.DeserializeObject<userinfo>(model.Muen.user);
            return new { data = model };
        }
后端代码

运行结果 我擦出错了报 415

 

{"message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource.","exceptionMessage":"No MediaTypeFormatter is available to read an object of type 'Testclass' from content with media type 'application/x-www-form-urlencoded'.","exceptionType":"System.Net.Http.UnsupportedMediaTypeException","stackTrace":"   在 System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   在 System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

大意是说不支持application/x-www-form-urlencoded 数据类型

那就从content-Type着手查阅资料

解决方法如下

修改content-Type 如下

 

 

运行测试--》运行正常

3、后台调用 api 传值

 

 ScanResultModel model = new ScanResultModel();
            model.Data = new List<SubmitOnlineStateModelItem>();
            model.Flag = true;
            model.RecordId = 2;
            model.TaskLogId = 33;

            string callback = "/api/action/method";
            string url = "http://localhost:14407/";

            var client = new RestClient(url + callback);
            //从发出请求开始算起,到与服务器建立连接的时间
            client.Timeout = 60 * 1000;
            //ReadWriteTimeout设置的是从建立连接开始,到下载数据完毕所历经的时间
            client.ReadWriteTimeout = 60 * 1000;
            var request = new RestRequest( Method.POST);
            request.AddHeader("Content-Type", "application/json; charset=utf-8");
            request.Parameters.Clear();
            request.AddParameter("application/json", JsonConvert.SerializeObject(model), ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            var content = response.Content;
            if (response.ErrorException != null)
            {
                return new { flag = true, msg = response.ErrorException.Message };
            }
            
            return new {flag = true,msg = content };
View Code

 

调用 api 方法

 public object ScanAllIp(ScanResultModel resultModel)
 {
    ..............
}

 

  • 总结

  webapi传值:

  1、设置 content-Type = ‘appliaction/json’ 

  2、传值(data)转换为字符串 JSON.stringify(data)

       3,mvc 的 action 和 webapi 方法,可以接受树形参数传值

  4、mvc和webapi参数名不区分大小写,newtonsoft.json 也不区分大小写

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM