Saranga
Saranga

Reputation: 520

cannot call post methods in asp

I can only call to asp GET methods using ajax. This is my JavaScript:

$scope.test = function () {
    var dataObject = {};
    dataObject.Company_Code = companyCode;
    $http({
        method: 'POST',
        url: 'http://localhost:31041/api/Location/test',
        data: $.param(dataObject),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Bearer ' + token
        }
    })
 .success(function (data) {    
 }).error(function () {
 });
}

And this is my WebAPI method:

[HttpPost]
public string test(Company_Details Company)
{
  return "11";
}

My global.asax settings:

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept,Authorization");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

When I try to invoke this method I receive the following error: enter image description here and also i can invoke post method with URL parameters(url: 'http://localhost:31041/api/Location/test?Name:123',). but cannot pass data using data: $.param(dataObject)

Upvotes: 0

Views: 55

Answers (3)

Wolf
Wolf

Reputation: 6499

look like you need use JSON.stringify for your data object

method: 'POST',
        url: 'http://localhost:31041/api/Location/test',
        data: JSON.stringify($.param(dataObject))

Upvotes: 0

Aswin Prabakaran
Aswin Prabakaran

Reputation: 25

Try this

[RoutePrefix("api/Location")]
[HttpPost]
[Route("test")]
public string test(Company_Details Company)
{
    return "11";
}

Upvotes: 0

Martin Brandl
Martin Brandl

Reputation: 58931

Try to add [FromBody] to the Company_Detailss parameter:

[HttpPost]
public string test([FromBody]Company_Details Company)
{
  return "11";
}

Upvotes: 1

Related Questions