首页 > 代码库 > 每日总结-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日