asp.net-web-api - 如何从 System.Web.Http.ModelBinding.IModelBinder 传递结果模型对象。绑定(bind)模型?

标签 asp.net-web-api odata asp.net-core-mvc

这是答案 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/

相关文章:

list - SharePoint 2010中如何获取列表的odata服务

asp.net - 将 ASP.NET 5 远程发布到 IIS

javascript - 如何使用 JavaScript 从 Bitfinex Web API 获取数据

asp.net-web-api - 使用apicontroller vs odata EntitySetController

c# - 仅为路由公开 .NET OData API 的子集(排除的 API 返回 404)

json - 如何使用 Breeze FilterQueryOp 忽略大小写

asp.net-core - 无法获取当前 http 请求的范围(Autofac 4)?

c# - 添加自定义声明在 ASP.NET Core Identity 中不起作用

Knockout.js 复杂对象绑定(bind)结果为空 HTML 输出

c# - 要调用此方法, "Membership.Provider"属性必须是 "ExtendedMembershipProvider"的实例