1

I trying to post to a api with accepts an integer parameter using angular as below

 function getDailyErrors() {
            var uri = "/api/users/error-counts/";
            var inData = { numberOfDays : 5}
            return $http.post(uri, inData)
                .then(function (response) {
                    return response.data;
                });
        }

API

 [HttpPost]
        [Route("api/users/error-counts/")]
        public MultiCategorySeriesDto<int> GetErrorCounts(int numberOfDays=15)
        {
            return _uow.Events.Errors(numberOfDays);
        }

for some reasons the API doesn't accept the parameter I passed instead takes the default int parameter. May I know where the mistake is?

1
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a minimal reproducible example. Commented Jun 16, 2017 at 19:21

3 Answers 3

1

Try using a view model:

public class MyViewModel
{
    public int NumberOfDays { get; set; }
}

that your controller action will take as parameter:

[HttpPost]
[Route("api/users/error-counts/")]
public MultiCategorySeriesDto<int> GetErrorCounts(MyViewModel model)
{
    return _uow.Events.Errors(model.NumberOfDays);
}
Sign up to request clarification or add additional context in comments.

Comments

0

As this is a POST, try using the [FromBody] attribute on the parameter to let the model binder know where to look for the data

[HttpPost]
[Route("api/users/error-counts/")]
public MultiCategorySeriesDto<int> GetErrorCounts([FromBody]int numberOfDays = 15)
{
    return _uow.Events.Errors(numberOfDays);
}

1 Comment

Does it accept optional parameters? because I get the exception "Optional parameter 'numberOfDays' is not supported by 'FormatterParameterBinding'."
0

The below code works fine for me, using the same API code as posted in your question.

    global.Himanshu.ErrorServices.factory('errorcountservices', ['$q', '$http', function ($q, $http) {
    return {getDailyErrors: fucntion()  {
            var deffered = $q.defer();
            $http({
                method: 'POST',
                url:/api/users/error-counts/',
                params: {
                    numberOfDays: 5
                },                    
            }).then(function (response) {
                deffered.resolve(response.data);
            },function (response) {
                deffered.reject(response.data);
            })
            return deffered.promise;
        }}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.