How to bind a request model in WebAPI GET request

2019-02-22 09:31发布

问题:

GET :http://www.Example.com/Api/1/0/Book/Company/0 

[Route("{UserId}/{Category}/books/{BookType}/{Page}")]
        [HttpGet]
        [RequestAuthorization]
         public Response Get(int UserId,string Category, string BookType,int Page )
        {          
            var books= this.contentService.GetUserItems(UserId,Category, BookType, Page)
            return new Response() { Status = ApiStatusCode.Ok, Books = books};
        }

The above code works well for me.

My question is is it possible to bind a request model in GET request ?

for example I have a request model like this

 public class BookbRequestModel
    {
        public int UserId { get; set; }
        public int Category { get; set; }
        public int Page { get; set; }  
        public string BookType { get; set; }       
    }

and i want my get request like this

GET :http://www.Example.com/Api/1/0/Book/Company/0 

to bind the data to my request model


[Route("{UserId}/{Category}/books/{BookType}/{Page}")]
        [HttpGet]
        [RequestAuthorization]
         public Response Get(BookbRequestModel book )
        {          
            var books= this.contentService.GetUserItems(book.UserId,book.Category,book.BookType,book.Page)
            return new Response() { Status = ApiStatusCode.Ok, Books = books};
        }

I tried this , but every time i get null in my book (BookRequestModel )

回答1:

add [FromUri] and try again as below

[Route("{UserId}/{Category}/books/{BookType}/{Page}")]
            [HttpGet]
            [RequestAuthorization]
             public Response Get(([FromUri] BookbRequestModel book )
            {          
                var books= this.contentService.GetUserItems(book.UserId,book.Category,book.BookType,book.Page)
                return new Response() { Status = ApiStatusCode.Ok, Books = books};
            }

for more information :-

http://www.c-sharpcorner.com/UploadFile/2b481f/parameter-binding-in-Asp-Net-web-api/



回答2:

It takes the parameters as they are you cannot do this. I would suggest try changing routeConfig. Add a new route. in WebApiConfig.cs.

config.Routes.MapHttpRoute(
                name: "NewApiRoute",
                routeTemplate: "myapi/{Controller}/{id}",
                defaults: new { id = new object()//this is to make it generic you can pass object of your class also }
                );