我有一个名为“TestController”的非常简单的C#APIController,其API方法为:
[HttpPost]
public string HelloWorld([FromBody] Testing t)
{
return t.Name + " " + t.LastName;
}
联系人只是一个类似这样的课程:
public class Testing
{
[Required]
public string Name;
[Required]
public string LastName;
}
我的APIRouter看起来像这样:
config.Routes.MapHttpRoute(
name: "TestApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
问题1 :
如何从C#客户端测试?
对于#2,我尝试了以下代码:
private async Task TestAPI()
{
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Name", "Happy"),
new KeyValuePair<string, string>("LastName", "Developer")
};
var content = new FormUrlEncodedContent(pairs);
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var result = await client.PostAsync(
new Uri("http://localhost:3471/api/test/helloworld",
UriKind.Absolute), content);
lblTestAPI.Text = result.ToString();
}
问题2 :
我如何从Fiddler测试这个?
似乎无法找到如何通过UI传递类。
答案 0 :(得分:28)
问题1: 我将从.NET客户端实现POST,如下所示。 请注意,您需要添加对以下程序集的引用: a)System.Net.Http b)System.Net.Http.Formatting
public static void Post(Testing testing)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:3471/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// Create the JSON formatter.
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
// Use the JSON formatter to create the content of the request body.
HttpContent content = new ObjectContent<Testing>(testing, jsonFormatter);
// Send the request.
var resp = client.PostAsync("api/test/helloworld", content).Result;
}
我还会按如下方式重写控制器方法:
[HttpPost]
public string HelloWorld(Testing t) //NOTE: You don't need [FromBody] here
{
return t.Name + " " + t.LastName;
}
问题2: 在Fiddler中,将Dropdown中的动词从GET更改为POST并输入JSON 请求正文中对象的表示