Reading FromUri and FromBody at the same time

送分小仙女□ 提交于 2019-11-26 09:48:18

问题


I have a new method in web api

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

where request class is like

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

I\'m making a query to localhost/Pusher/PushMessage?x=foo&y=bar with PostBody:

{ Message: \"foobar\" , TestingMode:true }

Am i missing something?


回答1:


A post body is typically a URI string like this:

Message=foobar&TestingMode=true

You have to make sure that the HTTP header contains

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

EDIT: Because it's still not working, I created a full 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));
    }
}



回答2:


The Web API uses naming regulations. The method for a post should be started with Post.

You should rename your PushMessage to method name PostMessage.

Also the web api defaulty listens (depending on your route) to 'api/values/Message' and not to Pusher/Pushmessage.

[HttpPost] attribute is not required




回答3:


You may use following code to post json in 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;


来源:https://stackoverflow.com/questions/12072277/reading-fromuri-and-frombody-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!