Fiddler testing API Post passing a [Frombody] clas

2020-06-08 04:40发布

I have this very simple C# APIController named "TestController" with an API method as:

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

Contact is just a class that look like this:

public class Testing
{
    [Required]
    public string Name;
    [Required]
    public string LastName;
}

My APIRouter looks like this:

config.Routes.MapHttpRoute(
     name: "TestApi",
     routeTemplate: "api/{controller}/{action}/{id}",
     defaults: new { id = RouteParameter.Optional }
);

QUESTION 1:
How can I test that from a C# Client?

For #2 I tried the following code:

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

QUESTION 2:
How can I test this from Fiddler?
Can't seem to find how to pass a Class via the UI.

1条回答
【Aperson】
2楼-- · 2020-06-08 05:37

For Question 1: I'd implement the POST from the .NET client as follows. Note you will need to add reference to the following assemblies: 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;

    }

I'd also rewrite the controller method as follows:

[HttpPost]
public string HelloWorld(Testing t)  //NOTE: You don't need [FromBody] here
{
  return t.Name + " " + t.LastName;
}

For Question 2: In Fiddler change the verb in the Dropdown from GET to POST and put in the JSON representation of the object in the Request body

enter image description here

查看更多
登录 后发表回答