Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - ASP.NET web api cannot get application/x-www-form-urlencoded HTTP POST

I'm new to web-api. I want to receive a HTTP POST data using web-api. The content-type is application/x-www-form-urlencoded, and the request body is like:

data={"mac":"0004ED123456","model":"SG6200NXL"}(JSON format).

My controller is like this:

public void Post([FromBody]string formData)
{
    data.Add(formData);
}

But formData is always null. Only when I change the request body to:

={"mac":"0004ED123456","model":"SG6200NXL"}

I can find {"mac":"0004ED123456","model":"SG6200NXL"} was saved in my formData string.

So my question is how should I receive the data with format:

data={"mac":"0004ED123456","model":"SG6200NXL"}?

And is there a easy way that I can desalinize the JSON into C#?

Thanks for help!

UPDATE: I tried to use model, but it still not work for me. My model is:

public class Device
    {
        public string mac { get; set; }
        public string model { get; set; }
    }

and my HTTP POST request is:

header:

User-Agent: Fiddler
Content-type: application/x-www-form-urlencoded
Host: localhost:52154
Content-Length: 46

body:

data={"mac":"0004ED123456","model":"SG6200NX"}

I have to use Content-type: application/x-www-form-urlencoded as far as I know because the HTTP POST is sent by a router. My job is to receive the data.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Quoting from here:

By default, Web API tries to get simple types from the request URI. The FromBody attribute tells Web API to read the value from the request body.

Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.

Second, the client needs to send the value with the following format:

=value

Specifically, the name portion of the name/value pair must be empty for a simple type.

So, if you want to post data in the format data=string, you have to create complex type.

public class MyFormData
{
    public string Data { get; set; }
}

And update your controller like so:

public void Post(MyFormData formData)
{
    //your JSON string will be in formData.Data
}

Of course, other alternatives for you is to change the content type to JSON, but really depends on your requirements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...