2

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

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

'IHeaderDictionary' does not contain a definition for 'GetValues' and no accessible extension method 'GetValues' accepting a first argument of type 'IHeaderDictionary' could be found (are you missing a using directive or an assembly reference?) I am using .net core 2. do I have to add any specific reference?
@Lauren Apparently that did method did not exist I changed my code with the correct method
cannot convert from 'out System.Collections.Generic.IEnumerable<string>' to 'out Microsoft.Extensions.Primitives.StringValues'
@Lauren Check my new edit , sorry for wasting a bit your time I should test things before post it in SO!
Should it be return new UnauthorizedResult();?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.