0

I can't for the life of me get this to work. I keep getting 404.

Here's the WebApi2 code:

[HttpPost]
    public IHttpActionResult Post(string testString)
    {
        if(!string.IsNullOrEmpty(testString))
        {
            return Ok(testString);
        }
        else
        {
            return BadRequest();
        }
    }

Here's the WebClient code:

 public async Task PostingToWebServiceShouldWork()
    {
        var apiEndPoint = new Uri(String.Format("{0}/Paging", ConfigurationManager.AppSettings["ApiEndpoint"].ToString()));
        var apiRoot = new Uri(apiEndPoint.GetLeftPart(UriPartial.Authority));
        var apiCall = apiEndPoint.PathAndQuery.Substring(1, apiEndPoint.PathAndQuery.Length - 1);
        using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
        {
            client.BaseAddress = apiRoot;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpContent content = new StringContent("testSTring");
            HttpResponseMessage response = await client.PostAsync(apiCall, content);

            if(response.IsSuccessStatusCode)
            {

            }
        }
    }

I just want to post a simple string to the web service. This should be dead simple, and it's giving me a migraine, lol. I've tried everything I can think of, and I have to be missing some tiny detail...

Thanks!

1 Answer 1

1

Because your API endpoint is simply a string instead of an object, WebAPI is looking for that string as a query string parameter. You have two options:

  1. Use the [FromBody] attribute in your action's definition

    public IHttpActionResult Post([FromBody] string testString)
    
  2. Send the string on the URL instead of in the body (works, but if you're going for security over HTTPS this exposes what you were posting)

See http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api for a deeper explanation and examples

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

3 Comments

Tried that, and I'm hitting the breakpoint in my service, but my parameter string value is "" (string.empty).... Is there a clear example of POSTing a simple string from c# to web api2 out there?
Can you post your code that posts to the web service? I'm wondering if your problem is actually somehow in the way you are doing that.
It was - finally pulled down Fiddler and found the problem - evidently using a StreamWriter was causing my issue. Went to a UTF-8 encoded byte[], used a normal Stream.Write, and now data is flowing as it should! Thanks for pointing me in the right direction :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.