【问题标题】:How to bind a request model in WebAPI GET request with route attribute?如何将 WebAPI GET 请求中的请求模型与路由属性绑定?
【发布时间】:2014-06-06 06:51:16
【问题描述】:
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)

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api get


    【解决方案1】:

    添加 [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/

    【讨论】:

    • 我想知道你能拥有模型的一部分FromUri和一部分FromBody吗?我有一个问题,我有一个FromBody 模型和一个字符串,模型已经过验证,我可以检查ModelState,但我必须自己验证字符串。 ParameterBindingAttribute可以放在模型内部的属性上吗?
    【解决方案2】:

    它接受参数,因为它们是你不能这样做的。我建议尝试更改 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 }
                    );
    

    【讨论】:

    • 如果您不知道答案,请至少阅读其他答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 2017-06-21
    • 2018-05-26
    • 2015-10-16
    • 2020-07-19
    • 2021-09-21
    相关资源
    最近更新 更多