27

我在 web api 中有一个新方法

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

请求类就像

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

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

{ Message: "foobar" , TestingMode:true }

我错过了什么吗?

4

3 回答 3

33

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

Message=foobar&TestingMode=true

您必须确保 HTTP 标头包含

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

编辑:因为它仍然无法正常工作,所以我自己创建了一个完整的示例。
它打印正确的数据。
我还使用了 .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));
    }
}
于 2012-08-22T11:48:05.203 回答
1

Web API 使用命名规则。帖子的方法应该以 Post 开头。

您应该将 PushMessage 重命名为方法名称 PostMessage。

此外,web api 默认侦听(取决于您的路由)“api/values/Message”而不是 Pusher/Pushmessage。

[HttpPost] 属性不是必需的

于 2012-11-30T10:07:28.610 回答
0

您可以使用以下代码在请求正文中发布 json:

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;
于 2012-08-23T07:40:10.827 回答