Lauren
Lauren

Reputation: 21

Web API .net core 2 request check the request's header is not empty

How can I verify whether the request's header some-header matches book's bookId?

    public IActionResult GetBooks()
    {
        // if 'some-header' value is empty, null , whitespace or request contains multiple ' some-header' headers then it should return UnauthorizedResult();
       // if 'some-header' is not above then it needs to be read from repository
    }
    public class Book 
    {
     public string bookId {get; set;}
    }

Upvotes: 2

Views: 3543

Answers (1)

Tiago Silva
Tiago Silva

Reputation: 2349

Request.Headers.GetValues() will return an IEnumerable<string> that correspond the headers from the HTTP request , then you can validate wether this contains multiple values or if its only one check if is null or white space ( which includes empty )

Request.Headers.TryGetValue("some-header", out var headers);         
if(headers.Count > 1 || string.IsNullOrWhiteSpace(headers.FirstOrDefault())){
   return new UnauthorizedResult();
}

Upvotes: 2

Related Questions