Diego
Diego

Reputation: 2362

Call Api Controller PostAsJsonAsync simple type parameter

I am calling a MVC Api Controller using PostAsJsonAsync.

If I want to pass a Complex type like a Class instance, it Works fine. But I need to pass a Simple type as string, or int like

HttpResponseMessage response = await
 client.PostAsJsonAsync("http://localhost:62536/api/Controller/Method", "HELLO");

Got an error 404 Method not found.

My WebApiController looks like this

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

My Api Controller Method looks like this.

public void Method(string id){}

If a try another Mehtod with Int type it does not work either..

 HttpResponseMessage response = await
     client.PostAsJsonAsync("http://localhost:62536/api/Controller/MethodA", 123);

public void MethodA(int id){}

If I assign that value to a Complex Type like a Class.. it Works fine.

PostAsJsonAsync only Works for complex Type? How can it make it work?

Upvotes: 1

Views: 2005

Answers (2)

Qaiser Mehmood
Qaiser Mehmood

Reputation: 212

public void Method([FromBody] string id){}

Upvotes: 5

Qaiser Mehmood
Qaiser Mehmood

Reputation: 212

Looks like parse issue. Create string variable first then pass to method.

string x = (string)value;

Upvotes: -1

Related Questions