标签:hash \n tor 返回 style query text exception creat
之前有一个用于七牛上传图片的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; } }
标签:hash \n tor 返回 style query text exception creat
原文地址:https://www.cnblogs.com/zitjubiz/p/9542455.html