0

I'm working on retrieving list of Movie Details from DB using WebAPi. I've http verbs and it does work as normal. I've a scenario where i've to get records based on categories like Title, Date, Rating
WebConfig:

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

Controller :

[HttpGet]
[GET("api/GetMovieByCategory/{movieData}")]
public IEnumerable<MovieData> GetMovieByCategory(MovieData movieData)  
    {
        IEnumerable<MovieData> movieDataByCat = null;
        string[] paramCast;
        if(movieData.Cast.Count()!=0)
        paramCast = movieData.Cast;
        IEnumerable<MovieData> GetAllMovies = null;
        GetAllMovies = repo.GetAll();`

        if (movieData.Cast == null || movieData.Cast.Count() == 0)
        {
            movieDataByCat = from data in GetAllMovies
                             where (data.Classification == (movieData.Classification == null ? string.Empty : movieData.Classification) ||
                                    data.Genre == (movieData.Genre == null ? string.Empty : movieData.Genre) ||
                                    data.Rating == movieData.Rating ||
                                    data.ReleaseDate == movieData.ReleaseDate ||
                                    data.Title == (movieData.Title == null ? string.Empty : movieData.Title))

                             select data;
        }
        return movieDataByCat;
    }

Angular Service :

//GetByCategory
this.getbyCat = function (Movie) {
    return $http.get("/api/values/GetMovieByCategory/" + Movie);
};

when i try to execute, i'm getting an exception as follows,

Remote Address:[::1]:50948
Request URL:http://localhost:50948/api/values/GetMovieByCategory/[object%20Object]
Request Method:GET
Status Code:404 Not Found

I've no idea how to overcome this and get it resolved. I'm in beginner level. Please help.

Rest of all verbs (get,put,post) are working fine.

Note : I've installed NugetPackage AttributeRouting.Web.Http; for Route.

Update 1 : Contoller.js :
$scope.srchbycat = function () { var Movie = { _title:"", _genre: "", _classification:"", _releaseDate: "", _rating: "", _cast: "" }; Movie = { _title: $scope.txttitle, _genre: $scope.txtGenre, _classification: $scope.txtClassification, _releaseDate: $scope.txtDate, _rating: $scope.user.txtRating, _cast: $scope.txtCast }; var promisePost = MyService.getbyCat(Movie);

Recent Error :
Remote Address:[::1]:50948 Request URL:http://localhost:50948/api/values/GetMovieByCategory/?_genre=sdf Request Method:GET Status Code:400 Bad Request

3
  • try this var movie = JSON.stringify({ movieData: Movie }); return $http.get("/api/values/GetMovieByCategory/" + movie ) Commented Nov 4, 2015 at 14:46
  • currently {movieData} is expecting a string, if you are passing it some non default(string) type of variable you need to tell it what to expect. Commented Nov 4, 2015 at 15:10
  • @Akshay i tried but got this, Remote Address:[::1]:50948 Request URL:http://localhost:50948/api/values/GetMovieByCategory/%7B%22movieData%22:%7B%22_genre%22:%22sdfsdf%22,%22_rating%22:%22%22%7D%7D Request Method:GET Status Code:400 Bad Request Commented Nov 4, 2015 at 15:13

1 Answer 1

1

In the Angular Service, instead of appending the Movie object, pass it as parameter.

eg.

//GetByCategory
this.getbyCat = function (Movie) {
    return $http.get("/api/values/GetMovieByCategory/", { params: Movie});
};

This will make the HTTP get with the the properties as url parameters.

And I dont think there is a need for the {movieData} parameter in the Route defined, since WebApi will automatically Serialize the url parameters to the object MovieData

eg.

index.js

angular.module('index.services', []).
factory('indexService', function ($http) {
      var api = 'api/values/GetData';
      var indexAPI = {};

      indexAPI.getData = function (params) {
          return $http.get(api, { params: params });
      }

      return indexAPI;
});
angular.module('index.controllers', ['index.services']).
controller('indexController', function ($scope, indexService) {
    $scope.getData = function () {
        var params = {
            name: 'test',
            age: '10'
        };
        $scope.errorOccured = false;
        indexService.getData(params).then(function (response) {
            $scope.data = response.data;
        }, function (response) {
            $scope.errorOccured = true;
        });
    }
});
angular.module('index', ['index.controllers']);

Index.cshtml

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular.js"></script>
<script src="~/Scripts/app/index.js"></script>
<div ng-app="index" ng-controller="indexController">
    <button ng-click="getData()">Get Data</button>
    <div ng-if="errorOccured==true">Error Occured</div>
    <div ng-repeat="item in data">
        <div>{{item}}</div>
    </div>
</div>

DataRequestModel.cs

public class DataRequestModel
{
    public string Name { get; set; }
    public string Age { get; set; }
}

ValuesController.cs

public class ValuesController : ApiController
{
    [HttpGet]
    public IEnumerable<string> GetData([FromUri]DataRequestModel dataRequest)
    {
        return new string[] { dataRequest.Name, dataRequest.Age.ToString() };
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

i've modified my route in APIController as [HttpGet] [GET("api/GetMovieByCategory/")] But still getting following exception on Submit, Request URL:http://localhost:50948/api/values/GetMovieByCategory/?_classification=sdf&_rating= Request Method:GET Status Code:400 Bad Request
Try removing the '/' at the end of the route. What are the properties in the C# class MovieData? The url parameters should exactly match the property names inside MovieData for the binding to occur properly.
Well it works half way. I could see the values which are being entered are there in Movie params in Service, but when it hits ApiController, MovieData is null.....what could be the reason?
Make sure the [FromUri] attribute is specified on the Action for the MovieData and the names of the properties match the url parameters. public IEnumerable<MovieData> GetMovieByCategory([FromUri] MovieData movieData)
I afraid I'm not getting it exactly. could you please point me broad
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.