Search code examples
c#asp.net-web-apihttp-postinternal-server-error

Cannot invoke HTTP POST method from C# - Internal Server Error


I have created a web api project and implemented the below HTTP POST method.

    [HttpPost, ActionName("updateProfile")]
    public IHttpActionResult updateProfile([FromBody]RequestDataModel request)
    {
        // MY CODE

    }

    public class RequestDataModel
    {
        public string FullName { get; set; }
        public int Age { get; set; }
    }

This is my WebAPIConfig class.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

And I tried to invoke this method from my C# application.

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var account = new { FullName = "Test", Age = 25 };

        StringContent content = new StringContent(JsonConvert.SerializeObject(account), Encoding.UTF8, "application/json");
        // HTTP POST
        var response = client.PostAsync("http://localhost:63648/api/Account/updateProfile", content);
        if (response.Result.IsSuccessStatusCode)
        {
           // MY CODE
        }
    }

But it returns an error as "Internal Server Error".

enter image description here


Solution

  • There is an issue in routeTemplate of WebApiConfig class.

    The routeTemplate should be api/{controller}/{action}/{id} instead of api/{controller}/{id}

    See below.

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