net core 模型绑定与之前版本的不同-FromBody 必须对应Json格式

之前有一个用于七牛上传图片的Callback Url的WebAPI (之前是用.net4.0,运行正常)

代码如下:

        // 七牛CallBack地址,CallbackBody内容name=upload/member/1.jpg&hash=Fn6qeQi4VDLQ347NiRm-RlQx_4O2
        public object Post([FromBody]dynamic data)
        {
            ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            logger.Info("data:" + data.ToString());
            int status = -1;

            try
            {
                string avator_url = data.name;
                int startPos = "upload/member/".Length;
                string member_id = avator_url.Substring(startPos, avator_url.IndexOf(".jpg") - startPos);
                MemberHelper.UpdateAvator(member_id, avator_url);
                var json = new { results = new string[0], status = 0 };
                return json;

            }
            catch (Exception ex)
            {
                string msg = ex.Message + ex.StackTrace;
                logger.Error("\r\n data:" + data.ToString() + "\r\nException:" + msg, ex);
                var json = new { results = new string[0], status = status, msg = msg };
                return json;

            }


        }

现在同样的代码在.net Core 却提示 HTTP 415 错误 – 不支持的媒体类型(Unsupported media type)

请参考这篇文章: https://www.cnblogs.com/CreateMyself/p/6246977.html

里面提到 ASP.NET MVC/WebAPi中无论是以表单POST的形式抑或JSON的形式控制器具有绑定都Http请求Body的能力同时数据都会返回给我们,我们不需要做出任何特别的说明

七牛CallBack的URL格式应该是用表单POST的形式(contentType: "application/x-www-form-urlencoded").

 

.net core mvc 模型绑定,默认的参数绑定类型是FromForm

 

FromQuery,对应 url 中的 urlencoded string ("?key1=value1&key2=value2")。


FromForm,对应 request content 中的 urlencoded string("key1=value1&key2=value2")。


FromBody,对应 request content 中的 JSON string("{"key1":"value1","key2":"value2"}")。

.NET Core 则严格限制了, Post([FromBody]dynamic data)  这个写法, 必须对应参数类型是JSON格式( contentType: "application/json"),否则会出现415错误  

我们可以做的就是写2个方法,无论七牛用那个方法去调用,都能正确返回.

 

        // 七牛CallBack地址,CallbackBody内容name=upload/member/memberId.jpg&hash=Fn6qeQi4VDLQ347NiRm-RlQx_4O2
        [AllowAnonymous]
        [HttpPost("updateAvatorJSON")]
        public object Post([FromBody]dynamic data)
        {
            int status = -1;

            try
            {
                updateAvator(data.name);
                var json = new { results = "", status = 0 };
                return json;

            }
            catch (Exception ex)
            {
                string msg = ex.Message + ex.StackTrace;
                var json = new { results = "", status = status, msg = msg };
                return json;

            }
        }
        [AllowAnonymous]
        [HttpPost("updateAvatorForm")]
        public object Post(string name, string hash)
        {
            int status = -1;

            try
            {
                updateAvator(name);
                var json = new { results = "", status = 0 };
                return json;

            }
            catch (Exception ex)
            {
                string msg = ex.Message + ex.StackTrace;
                var json = new { results = "", status = status, msg = msg };
                return json;

            }
        }

 

 

**********后记---- 在微信小程序wx.request时,再次碰到类似的问题*************

客户端:

    wx.request({
      url: url,
      method: 'POST',
      header: { "Content-Type": "application/x-www-form-urlencoded" },
      data: dataParam,
      success: function (res) {

      }})

对应的服务器端代码必须用[FromForm]修饰,不然取不到数据. 因为.net core 默认只找QueryString

 [HttpPost]
        public dynamic Post(            
            [FromForm]string CustomOrderNumber,
            [FromForm]int CustomerId
            )
        {}

------------------------------------------------------------------------------------------------------

如果 客户端用 "Content-Type": "application/json", 则服务器端必须用[FromBody]

 

------------------------------------------------------------------------------------------------------

服务器端的[FromForm]和[FromBody]不能混用, api接口要么就一个大对象,要么就要把其他的参数放在QueryString里

        public dynamic Post(            
            string CustomOrderNumber,
            int CustomerId,
            [FromBody]OrderItemDTO[] Items
            )

 

转载于:https://www.cnblogs.com/zitjubiz/p/9542455.html

你可能感兴趣的:(net core 模型绑定与之前版本的不同-FromBody 必须对应Json格式)