user3266638
user3266638

Reputation: 449

Posting to web api

What would be the best or better way to handle posting to a web api and how would it be done via C#?

Web API code

public class ProcessController : ApiController
{
    [HttpGet]
    public string Test()
    {
        return "Hello from API";
    }


    [HttpPost]
    public IHttpActionResult ApiPost(Model m)
    {
        return Ok();
    }
}

public class Model
{
    public int Id {get; set;}
    public string Name {get; set;}
}

Code to call web api

HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
client.BaseAddress = new Uri("http://localhost:2478/api/Process/");

HttpResponseMessage response = await client.GetAsync("test");

Model m = new Model ();
m.Id= 4;
m.Name = "test";

var r = client.PostAsJsonAsync("ApiPost", m);

This returns a 500 internal server error. Is there something missing here?

Web API config

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        settings.Formatting = Formatting.Indented;

        config.MapHttpAttributeRoutes();

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

    }
}

Upvotes: 0

Views: 73

Answers (2)

user3266638
user3266638

Reputation: 449

Changing the routing code to include the action fixed the issue. It looks like the code to call the web API worked fine so long as their was one GET or POST method as any call would try to use one of those.

Without the action it did not know which method to use in the API controller as it could not route to it.

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional }
        );
    }

Upvotes: 1

Andy
Andy

Reputation: 2354

Have you tried this: add the FromBody attribute to your model and post a model that matches m in the body

[HttpPost]
public IHttpActionResult ApiPost([FromBody] Model m)
{
    return Ok();
}

Upvotes: 1

Related Questions