如何将WebAPI GET请求中的请求模型绑定到路由属性? [英] How to bind a request model in WebAPI GET request with route attribute?

查看:153
本文介绍了如何将WebAPI GET请求中的请求模型绑定到路由属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

我的问题是可以在GET请求中绑定请求模型吗?

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; }       
    }

我想要这样的请求

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};
        }

我试过这个,但是每次我在我的书(BookRequestModel)

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

推荐答案

添加[FromUri]并再次尝试如下

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/

这篇关于如何将WebAPI GET请求中的请求模型绑定到路由属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆