Reading FromUri and FromBody at the same time

I have a new method in web api

[HttpPost] public ApiResponse PushMessage( [FromUri] string x, [FromUri] string y, [FromBody] Request Request) 

where the request class is similar to

 public class Request { public string Message { get; set; } public bool TestingMode { get; set; } } 

Am I making a request to localhost / Pusher / PushMessage? x = foo & y = bar with PostBody:

 { Message: "foobar" , TestingMode:true } 

Am I missing something?

+22
c # asp.net-web-api
Aug 22 2018-12-12T00:
source share
3 answers

The body of the message is usually a URI string as follows:

 Message=foobar&TestingMode=true 

You must ensure that the HTTP header contains

 Content-Type: application/x-www-form-urlencoded 

EDIT : since it still doesn't work, I created a complete example myself.
It prints the correct data.
I also used .NET 4.5 RC.

 // server-side public class ValuesController : ApiController { [HttpPost] public string PushMessage([FromUri] string x, [FromUri] string y, [FromBody] Person p) { return p.ToString(); } } public class Person { public string Name { get; set; } public int Age { get; set; } public override string ToString() { return this.Name + ": " + this.Age; } } // client-side public class Program { private static readonly string URL = "http://localhost:6299/api/values/PushMessage?x=asd&y=qwe"; public static void Main(string[] args) { NameValueCollection data = new NameValueCollection(); data.Add("Name", "Johannes"); data.Add("Age", "24"); WebClient client = new WebClient(); client.UploadValuesCompleted += UploadValuesCompleted; client.Headers["Content-Type"] = "application/x-www-form-urlencoded"; Task t = client.UploadValuesTaskAsync(new Uri(URL), "POST", data); t.Wait(); } private static void UploadValuesCompleted(object sender, UploadValuesCompletedEventArgs e) { Console.WriteLine(Encoding.ASCII.GetString(e.Result)); } } 
+25
Aug 22 '12 at 11:48
source share

The web API uses naming conventions. The message method must begin with a message.

You must rename your PushMessage to the name of the PostMessage method.

In addition, the web api listens by default (depending on your route) for the value "api / values ​​/ Message" rather than "Pusher / Pushmessage".

[HttpPost] attribute not required

+1
Nov 30 '12 at 10:07
source share

You can use the following code to send json to the request body:

 var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Request request = new Request(); HttpResponseMessage response = httpClient.PostAsJsonAsync("http://localhost/Pusher/PushMessage?x=foo&y=bar", request).Result; //check if (response.IsSuccessStatusCode) var createResult = response.Content.ReadAsAsync<YourResultObject>().Result; 
0
Aug 23 '12 at 7:40
source share



All Articles