读FromUri和FromBody同时 [英] Reading FromUri and FromBody at the same time

查看:3703
本文介绍了读FromUri和FromBody同时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网页API的新方法

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; }
}

我正在做一个查询到localhost /推/ PushMessage X =富&安培; Y =有PostBody吧?

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

{ Message: "foobar" , TestingMode:true }

我缺少的东西?

Am i missing something?

推荐答案

一个后身体通常是一个URI字符串是这样的:

A post body is typically a URI string like this:

Message=foobar&TestingMode=true

您必须确保在HTTP头中包含

You have to make sure that the HTTP header contains

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

修改:因为它仍然没有工作,我创建了一个完整的例子我结果。
它打印出正确的数据。结果
我还使用.NET 4.5 RC。

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));
    }
}

这篇关于读FromUri和FromBody同时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆