这是答案 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?
}
最佳答案
我假设您的问题与 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中你可以注册很多modelbinder(其中一些是默认注册的),还有一些你注册的并且都实现了IModelBinder。因此,当它尝试解析请求数据时,它会转到许多模型绑定(bind)程序,当您在 BindModel 中返回 true 时,它将停在那里,之后的所有模型绑定(bind)程序都会被丢弃。
更多详细信息可以在此处找到。 (您可以在其中看到模型绑定(bind)器部分) http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
关于asp.net-web-api - 如何从 System.Web.Http.ModelBinding.IModelBinder 传递结果模型对象。绑定(bind)模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28892332/