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请求中绑定请求模型吗?
例如,我有一个像这样的请求模型
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};
}
我试过这个,但每次我在我的书中都得到null(BookRequestModel)
答案 0 :(得分:8)
添加[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/
答案 1 :(得分:-3)
它需要参数,因为它们不能这样做。我建议尝试更改routeConfig。
添加新路线。在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 }
);