这是答案https://stackoverflow.com/a/10099536/3481183
的后续问题现在我可以成功提取内容,应用反序列化并获取我想要的对象。如何将其传递给动作?提供的函数BindModel
必须返回bool
值,这对我来说非常混乱。
我的代码:
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
actionContext.Request.Content.ReadAsStringAsync().ContinueWith(deserialize);
return true;
}
#endregion
#region Methods
private static void deserialize(Task<string> content)
{
string formData = content.Result; // {"content":"asdasd","zip":"12321","location":"POINT (1 2)"}
Match locationMatch = Regex.Match(
formData,
@"""location"":""POINT(.+)""",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (!locationMatch.Success)
{
throw new ModelValidationException("Post data does not contain location part");
}
string locationPart = locationMatch.Value;
formData = formData.Replace(locationPart, string.Empty);
var serializer = new JavaScriptSerializer();
var post = serializer.Deserialize<Post>(formData);
post.Location = DbGeography.FromText(locationPart);
// how am I supposed to pass `post` to the action method?
}
答案 0 :(得分:2)
我认为您的问题与Web API有关(与ASP.net vnext无关)。假设的原因是您在示例中提供的方法以及旧问题。
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
actionContext.Request.Content.ReadAsStringAsync().ContinueWith(deserialize);
bindingContext.Model = your model; // You can return from static method or you can pass bindingContext to static method and set model over there.
return true;
}
现在关于你的困惑。
在Web API中,您可以注册许多模型绑定器(其中一些默认注册)和一些您注册的并且都实现了IModelBinder。因此,当它尝试解析请求数据时会转到许多模型绑定器,当你在BindModel中返回true时,它将停在那里,之后所有的模型绑定器都会被丢弃。
可在此处找到更多详细信息。 (您可以看到模型粘合剂部分) http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api