首页 > 解决方案 > Web API .net core 2 request 检查请求头不为空

问题描述

如何验证请求的标头 some-header 是否与书的 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;}
    }

标签: c#asp.net-web-apiasp.net-core-webapihttpresponse

解决方案


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

推荐阅读