17

我有一个名为“TestController”的非常简单的 C# APIController,其 API 方法为:

[HttpPost]
public string HelloWorld([FromBody] Testing t)
{
    return t.Name + " " + t.LastName;
}

Contact 只是一个看起来像这样的类:

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 传递一个类。

4

1 回答 1

29

对于问题 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 中,将下拉菜单中的动词从 GET 更改为 POST,并将对象的 JSON 表示形式放入请求正文中

在此处输入图像描述

于 2013-10-16T06:51:38.403 回答