Fiddler testing API Post passing a [Frombody] class

前端 未结 1 659
独厮守ぢ
独厮守ぢ 2021-02-12 23:57

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

[HttpPost]
public string HelloWorld([FromBody] Testing t)
{
    return t         


        
相关标签:
1条回答
  • 2021-02-13 00:55

    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

    0 讨论(0)
提交回复
热议问题