本文介绍了如何将 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};
}
了解更多信息:-
http://www.c-sharpcorner.com/UploadFile/2b481f/parameter-binding-in-Asp-Net-web-api/
这篇关于如何将 WebAPI GET 请求中的请求模型与路由属性绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!