Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The following URL maps to the action below: /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; }
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...