c# - 如何使用路由属性绑定(bind) WebAPI GET 请求中的请求模型?

标签 c# asp.net-mvc asp.net-web-api 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};
        }

上面的代码对我来说效果很好。

我的问题是是否可以在 GET 请求中绑定(bind)请求模型?

例如我有这样一个请求模型

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

我想要这样的 get 请求

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

我试过了,但每次我在我的书中得到 null (BookRequestModel)

最佳答案

添加 [FromUri] 然后重试如下

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

更多信息:-

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

关于c# - 如何使用路由属性绑定(bind) WebAPI GET 请求中的请求模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24075892/

相关文章:

c# - WCF Web API 和 ASP.NET Web API 有什么区别

c# - 列表不会用 protobuf 序列化

c# - 将数据从 Model 导入 View 时出现无法解决的错误

asp.net-mvc - .Net MVC 将嵌套数据从 Controller 传递到 View

asp.net-web-api - mvc webapi 跨域发布

ajax - Rest API - 405 方法不允许

c# - 为什么我看不到内容编码 : gzip response in my c# HttpClient response header?

c# - 使用 Shadow Copy 启动的 CefSharp 应用程序

c# - 当一个对象被垃圾回收时,是否释放了未处置的资源?

c# - 请求在 Helper 方法上被中止 : The connection was closed unexpectedly.