Fiddler测试API Post传递类
我有一个名为“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> { new KeyValuePair("Name", "Happy"), new KeyValuePair("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传递类。
问题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, 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并在Request主体中放入对象的JSON表示
- HttpClient调用Windows-Authenication ApiController方法…但没有WindowsIdentity出现
- 名为“DefaultRoute”的路径已在路径集合中。 路线名称必须是唯一的
- 使用HttpClient将字节数组发布到Web API服务器
- container.RegisterWebApiControllers(GlobalConfiguration.Configuration)导致InvalidOperationException
- 使用命令参数的Web API不返回任何数据
- 如何通过FromBody将DataTable传递给Web API POST方法(C#)
- 从catch块向客户端发送格式化的错误消息
- 使用AngularJS和ASP.NET Web API上载/下载字节数组
- WebApi POST不包含ID字段