首页 > 代码库 > 每日总结-2015年1月13日
每日总结-2015年1月13日
MVC写API接口遇到问题
[HttpPost] [POST("alterScriptParams")] public bool AlterScriptParamsByScriptName(string scriptName,string scriptParams) { var agencyDatasetScriptBusinessEntity = IocContainer.Resolve<IAgencyDatasetScriptBusinessEntities>(); return agencyDatasetScriptBusinessEntity.AlterScriptParamsByScriptName(scriptName, scriptParams); }
测试接口报 No HTTP resource was found...错误
我测试接口body内填的是{"scriptName":"xx","scriptParams","yy"},一开始以为是方法内部错误所以找不到资源,弄了很久,网上找到问题根源:
http://weblog.west-wind.com/posts/2013/Dec/13/Accepting-Raw-Request-Body-Content-with-ASPNET-Web-API#[FromBody]toretrieveContent
改成:
public string PostJsonString([FromBody] string text)
或 对象:
[HttpPost] [POST("alterScriptParams")] public bool AlterScriptParamsByScriptName(WSDataScript model) { var agencyDatasetScriptBusinessEntity = IocContainer.Resolve<IAgencyDatasetScriptBusinessEntities>(); return agencyDatasetScriptBusinessEntity.AlterScriptParamsByScriptName(model.ScriptName, model.ScriptParams); }
能解决,问题的关键是用对象的话内部会帮你自动匹配,“If the data happens to be POST form data (ie. urlencoded key value pairs), Web API’s Model Binding can automatically map each of the keys of the form data to the properties of the object, including nested object paths.So that‘s very easy and as it should be, and it actually addresses most of the realistic use cases. This is the ‘complex stuff is easy’ part.”
每日总结-2015年1月13日
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。