2

I have an Asp Net Core 2.1 application with a REST controller like this:

[Produces("application/json")]
[Route("api/Test")]
public class TestController : Controller
{
    // GET: api/Test
    [HttpGet]
    public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }

    // GET: api/Test/5
    [HttpGet("{id}", Name = "Get")]
    public string Get(int id) { return "value"; }

    // POST: api/Test
    [HttpPost]
    public void Post([FromBody]string value)
    {
        //.. testing code..
    }

    // PUT: api/Test/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value) {}

    // DELETE: api/ApiWithActions/5
    [HttpDelete("{id}")]
    public void Delete(int id) {}
}

I'm trying to use "System.Net.HttpWebRequest" object to make a POST request to Rest controller. In my client application, I have a method that receives data as a string.
The string content is a dynamic array of values such "param1=value1;param2=value2" (the number of elements is variable).
Can you help me to understand the correct way to send this data to the controller?

this is the code I'm trying to use in the client:

public static string PostWebApi(string postData)
{    
    var request = (HttpWebRequest)WebRequest.Create("http://localhost:64817/api/test");

    // for example, assumes that postData value is "param1=value1;param2=value2"
    var data = Encoding.ASCII.GetBytes(postData);

    request.Method = "POST";
    request.ContentType = "application/json";
    //request.ContentType = "application/x-www-form-urlencoded";

    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream()) {
        stream.Write(data, 0, data.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

    return responseString;
}

I'm using content type "application/json": if I try to use "application/x-www-form-urlencoded" I get "(415) Unsupported Media Type" error.
so... when I exec PostWebApi I receive a Null value parameter in the POST: api/Test method..
how can I receive the data I sent?

Thanks in advance.

2
  • could you show your sample "postData" string? Commented Jul 2, 2018 at 10:38
  • You could create a simple object PostData with one property of type string Value in it and send the object as json. Change Api to get this type of object Commented Jul 2, 2018 at 10:39

1 Answer 1

3

you can use HTTPClient for this. it'll ease up the process for you.

public static string PostWebApi(string postData)
{           
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:64817/api/test");
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("value", postData)
            });
            var result = await client.PostAsync("/api/Membership/exists", content);
            string resultContent = await result.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
        }
}

Reference:- How to make HTTP POST web request

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.