-2

I want to follow proper URL convention and use hyphen as word delimiter: /api/books?author-id=3

But property names with hyphen are not supported in C#. How can I bind AuthorId to author-id in .NET Framework 4.8?

As an example, consider this URL: /api/books?authorid=3

It maps to the method below.

[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; }
}
Jam
  • 386
  • 2
  • 13

1 Answers1

1

try this for url ..../api/books?author-id=3&genre-id=5 . It works for all net versions

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

parameters

 public class BooksParameters
 {
        public int? AuthorId { get; set; }
        public int? BookId { get; set; }
 }
Serge
  • 40,935
  • 4
  • 18
  • 45
  • This is not very scalable for multiple methods... – Tvde1 Oct 01 '21 at 13:28
  • @Tvde1 There is nothing about multiple methods in the question. It is not a free coding resource and I am not going to spend the whole day creating a library. It is just a hint for PO. – Serge Oct 01 '21 at 13:30