Web 中带连字符的参数 API 2

Parameter with hyphen in Web API 2

我想关注 proper URL convention 并使用连字符作为单词分隔符:/api/books?author-id=3

但是 属性 C# 不支持带连字符的名称。如何在 .NET Framework 4.8 中将 AuthorId 绑定到 author-id

例如,考虑这个 URL:/api/books?authorid=3

它映射到下面的方法。

[RoutePrefix("api/books")]
public class BooksController
{
    [HttpGet]
    public async Task<IHttpActionResult> GetBooks([FromUri] GetBooksParameters getBooksParameters)
    {
        var authorId = getBooksParameters.AuthorId;
        // ...
    }
}

public class GetBooksParameters
{
    public int? AuthorId { get; set; }
}

试试这个 url ..../api/books?author-id=3&genre-id=5 。它适用于所有网络版本

 [HttpGet]
    public async Task<IHttpActionResult> GetBooks()
    {
       var parameters = GetBooksParameters(HttpContext);
    // ...
   }

    [NonAction]
    private BooksParameters GetBooksParameters(HttpContext httpContext)
    {
        var parameters = new BooksParameters();

        var queryString = httpContext.Request.QueryString.Value;

        foreach (string item in queryString.Split('&'))
        {
            string[] parts = item.Replace("?", "").Split('=');

            switch (parts[0])
            {
                case "author-id":
                    parameters.AuthorId = Convert.ToInt32(parts[1]);
                    break;
                case "book-id":
                    parameters.BookId = Convert.ToInt32(parts[1]);
                    break;

                default:
                    break;
            }
        }
        return parameters;
    }

参数

 public class BooksParameters
 {
        public int? AuthorId { get; set; }
        public int? BookId { get; set; }
 }