Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm sending a request to server in the following form:

http://localhost:12345/api/controller/par1/par2

The request is correctly resolved to a method like:

[HttpPost]
public void object Post(string par1, string par2)

However, I pass additional data through the request content. How can I retrieve these data?

For the sake of example, let's say, that the request is sent from the form:

<form action="http://localhost:12345/api/controller/par1/par2" method="post">
    <input type="hidden" name="data" value="value" />
    <input type="submit" name="submit" value="Submit" />
</form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
519 views
Welcome To Ask or Share your Answers For Others

1 Answer

From answer in this question: How to get Json Post Values with asp.net webapi

  1. Autoparse using parameter binding; note that the dynamic is made up of JToken, hence the .Value accessor.

    public void Post([FromBody]dynamic value) {
        var x = value.var1.Value; // JToken
    }
    
  2. Read just like Request.RequestUri.ParseQueryString()[key]

    public async Task Post() {        
       dynamic obj = await Request.Content.ReadAsAsync<JObject>();
       var y = obj.var1;
    }
    
  3. Same as #2, just not asynchronously (?) so you can use it in a helper method

    private T GetPostParam<T>(string key) {
        var p = Request.Content.ReadAsAsync<JObject>();
        return (T)Convert.ChangeType(p.Result[key], typeof(T)); // example conversion, could be null...
    }
    

Caveat -- expects media-type application/json in order to trigger JsonMediaTypeFormatter handling.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...