同时阅读FromUri和FromBody

kko*_*yik 24 c# asp.net http-post asp.net-web-api frombodyattribute

我在web api中有一个新方法

[HttpPost]
public ApiResponse PushMessage( [FromUri] string x, [FromUri] string y, [FromBody] Request Request)
Run Code Online (Sandbox Code Playgroud)

请求类就像

public class Request
{
    public string Message { get; set; }
    public bool TestingMode { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用PostBody对localhost/Pusher/PushMessage进行查询?x = foo&y = bar:

{ Message: "foobar" , TestingMode:true }
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

Joh*_*ger 30

帖子正文通常是这样的URI字符串:

Message=foobar&TestingMode=true
Run Code Online (Sandbox Code Playgroud)

您必须确保HTTP标头包含

Content-Type: application/x-www-form-urlencoded
Run Code Online (Sandbox Code Playgroud)

编辑:因为它仍然无法正常工作,我自己创建了一个完整的例子.
它打印正确的数据.
我还使用了.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));
    }
}
Run Code Online (Sandbox Code Playgroud)