how to pass the result model object out of System.

2019-07-20 15:25发布

This is a follow up question to the answer https://stackoverflow.com/a/10099536/3481183

Now that I could successfully extracted the content, apply deserialization and obtain the object that I want. How do I pass it to the action? The provided function BindModel must return a bool value, which is very confusing to me.

My code:

    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?
    }

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-20 15:35

I assume that your question is related to Web API ( Not relate to ASP.net vnext). Reason for assumption is that method you provided in example as well as old question.

 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;
    }

Now regarding your confusion.

In Web API you can register many modelbinder ( Some of them default registered) and some you registered and all implement IModelBinder. So when it try to parse request data then it goes to many model binder and when you return true in BindModel it will stop over there and all modelbinder after that get discarded.

More detail can be found here. ( In that you can see section Model Binders) http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

查看更多
登录 后发表回答