SF *_*per 16 c# fiddler asp.net-web-api
我有一个名为"TestController"的非常简单的C#APIController,其API方法如下:
[HttpPost]
public string HelloWorld([FromBody] Testing t)
{
return t.Name + " " + t.LastName;
}
Run Code Online (Sandbox Code Playgroud)
联系人只是一个类似于以下的类:
public class Testing
{
[Required]
public string Name;
[Required]
public string LastName;
}
Run Code Online (Sandbox Code Playgroud)
我的APIRouter看起来像这样:
config.Routes.MapHttpRoute(
name: "TestApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
问题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();
}
Run Code Online (Sandbox Code Playgroud)
问题2:
如何从Fiddler测试这个?
似乎无法找到如何通过UI传递类.
Abh*_*tel 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;
}
Run Code Online (Sandbox Code Playgroud)
我还要重写控制器方法如下:
[HttpPost]
public string HelloWorld(Testing t) //NOTE: You don't need [FromBody] here
{
return t.Name + " " + t.LastName;
}
Run Code Online (Sandbox Code Playgroud)
对于问题2:在Fiddler中,将Dropdown中的动词从GET更改为POST,并在Request主体中放入对象的JSON表示形式

| 归档时间: |
|
| 查看次数: |
44094 次 |
| 最近记录: |