0

I created WebAPI service. I have controller in the service, and it looks like:

public class MyController : ApiController
{
    [HttpPost]
    public ResponceTools.APIResponce UserLoggedIn(UserArgs args)
    {
        //doing something    
    }
}

where

public class UserArgs
{
    public string UserID { get; set; }
}

I can send request to the the method UserLoggedIn and give adequate response using curl :

curl --data "UserID=7822f2b9-44f1-4e30-a9da-d26e277fa0ac" http://localhost:8081/UserLoggedIn"

Now I'm writing .net Core Web App, and I want to use this service.

string requestStr = WebAPIURL + "/UserLoggedIn";
var content = new StringContent("UserID=" + userID.ToString(), 
                                 System.Text.Encoding.Unicode, 
                                 "application/xml");            
var task = client.PostAsync(requestStr, content);
var str = await task.Result.Content.ReadAsStringAsync();    

but the method args value is null.

What am I doing wrong?

P.S. I tried to activate XmlSerializer in my WebApi application in "Register" method. It does not help.

config.Formatters.XmlFormatter.UseXmlSerializer = true;

Thank you for any help.

2
  • var task = client.PostAsync(requestStr + "?UserId="+userID.tostring, content); // don't know may be this works Commented Apr 18, 2017 at 4:28
  • Your content type is xml but you're not sending xml. Commented Apr 18, 2017 at 5:49

2 Answers 2

2

Instead of sending the UserID as a string you should send it as an object to make it match the class definition of UserArgs.

var user = { UserID: userID };

Then send that object by the content type of application/json as that is the default deserializer in web api.

var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I didn't know that JSON is default Serializer for Web API.
0

It must be sufficient to change content type

var content = new StringContent("UserID=" + userID.ToString(), 
                             System.Text.Encoding.Unicode, 
                             "application/x-www-form-urlencoded"); 

You are sending request data that are not XML or JSON so this content type is the only one suitable. If you want to know more about binding you can see this article (https://andrewlock.net/model-binding-json-posts-in-asp-net-core/)

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.