Skip to content

Commit 54deae7

Browse files
author
Bart Koelman
committed
Resolved new warnings
1 parent 5e40e1a commit 54deae7

File tree

17 files changed

+57
-41
lines changed

17 files changed

+57
-41
lines changed

benchmarks/LinkBuilder/LinkBuilderGetNamespaceFromPathBenchmarks.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ private static void GetNamespaceFromPathUsingReadOnlySpan(string path, string re
6767

6868
if (isAtEnd || hasDelimiterAfterSegment)
6969
{
70-
_ = pathSpan.Slice(0, index).ToString();
70+
_ = pathSpan[..index].ToString();
7171
}
7272
}
7373
}

src/JsonApiDotNetCore/Configuration/JsonApiValidationFilter.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public bool ShouldValidateEntry(ValidationEntry entry, ValidationEntry parentEnt
4141

4242
var httpContextAccessor = _serviceProvider.GetRequiredService<IHttpContextAccessor>();
4343

44-
if (httpContextAccessor.HttpContext.Request.Method == HttpMethods.Patch || request.OperationKind == OperationKind.UpdateResource)
44+
if (httpContextAccessor.HttpContext!.Request.Method == HttpMethods.Patch || request.OperationKind == OperationKind.UpdateResource)
4545
{
4646
var targetedFields = _serviceProvider.GetRequiredService<ITargetedFields>();
4747
return IsFieldTargeted(entry, targetedFields);

src/JsonApiDotNetCore/Middleware/FixedQueryFeature.cs

+9-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public IQueryCollection Query
2727
{
2828
get
2929
{
30-
if (_features.Collection == null)
30+
if (IsFeatureCollectionNull())
3131
{
3232
return _parsedValues ??= QueryCollection.Empty;
3333
}
@@ -49,7 +49,7 @@ public IQueryCollection Query
4949
{
5050
_parsedValues = value;
5151

52-
if (_features.Collection != null)
52+
if (!IsFeatureCollectionNull())
5353
{
5454
if (value == null)
5555
{
@@ -77,5 +77,12 @@ public FixedQueryFeature(IFeatureCollection features)
7777

7878
_features.Initalize(features);
7979
}
80+
81+
private bool IsFeatureCollectionNull()
82+
{
83+
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
84+
// Justification: This code was copied from the ASP.NET sources. A struct instance can be created without calling one of its constructors.
85+
return _features.Collection == null;
86+
}
8087
}
8188
}

src/JsonApiDotNetCore/Middleware/JsonApiMiddleware.cs

+4-2
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ private static async Task<bool> ValidateContentTypeHeaderAsync(string allowedCon
125125
{
126126
string contentType = httpContext.Request.ContentType;
127127

128+
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
129+
// Justification: Workaround for https://github.com/dotnet/aspnetcore/issues/32097 (fixed in .NET 6)
128130
if (contentType != null && contentType != allowedContentType)
129131
{
130132
await FlushResponseAsync(httpContext.Response, serializerSettings, new Error(HttpStatusCode.UnsupportedMediaType)
@@ -280,9 +282,9 @@ private static string GetCustomRoute(string resourceName, string apiNamespace, H
280282
if (resourceName != null)
281283
{
282284
Endpoint endpoint = httpContext.GetEndpoint();
283-
var routeAttribute = endpoint.Metadata.GetMetadata<RouteAttribute>();
285+
var routeAttribute = endpoint?.Metadata.GetMetadata<RouteAttribute>();
284286

285-
if (routeAttribute != null)
287+
if (routeAttribute != null && httpContext.Request.Path.Value != null)
286288
{
287289
List<string> trimmedComponents = httpContext.Request.Path.Value.Trim('/').Split('/').ToList();
288290
int resourceNameIndex = trimmedComponents.FindIndex(component => component == resourceName);

src/JsonApiDotNetCore/QueryStrings/Internal/RequestQueryStringAccessor.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ internal sealed class RequestQueryStringAccessor : IRequestQueryStringAccessor
77
{
88
private readonly IHttpContextAccessor _httpContextAccessor;
99

10-
public IQueryCollection Query => _httpContextAccessor.HttpContext.Request.Query;
10+
public IQueryCollection Query => _httpContextAccessor.HttpContext!.Request.Query;
1111

1212
public RequestQueryStringAccessor(IHttpContextAccessor httpContextAccessor)
1313
{

src/JsonApiDotNetCore/Serialization/Building/LinkBuilder.cs

+6-6
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,8 @@ private bool ShouldIncludeTopLevelLink(LinkTypes linkType, ResourceContext resou
102102
private string GetLinkForTopLevelSelf()
103103
{
104104
return _options.UseRelativeLinks
105-
? _httpContextAccessor.HttpContext.Request.GetEncodedPathAndQuery()
106-
: _httpContextAccessor.HttpContext.Request.GetEncodedUrl();
105+
? _httpContextAccessor.HttpContext!.Request.GetEncodedPathAndQuery()
106+
: _httpContextAccessor.HttpContext!.Request.GetEncodedUrl();
107107
}
108108

109109
private void SetPaginationInTopLevelLinks(ResourceContext requestContext, TopLevelLinks links)
@@ -133,7 +133,7 @@ private void SetPaginationInTopLevelLinks(ResourceContext requestContext, TopLev
133133

134134
private string CalculatePageSizeValue(PageSize topPageSize, ResourceContext requestContext)
135135
{
136-
string pageSizeParameterValue = _httpContextAccessor.HttpContext.Request.Query[PageSizeParameterName];
136+
string pageSizeParameterValue = _httpContextAccessor.HttpContext!.Request.Query[PageSizeParameterName];
137137

138138
PageSize newTopPageSize = Equals(topPageSize, _options.DefaultPageSize) ? null : topPageSize;
139139
return ChangeTopPageSize(pageSizeParameterValue, newTopPageSize, requestContext);
@@ -188,7 +188,7 @@ private string GetLinkForPagination(int pageOffset, string pageSizeValue)
188188
{
189189
string queryStringValue = GetQueryStringInPaginationLink(pageOffset, pageSizeValue);
190190

191-
var builder = new UriBuilder(_httpContextAccessor.HttpContext.Request.GetEncodedUrl())
191+
var builder = new UriBuilder(_httpContextAccessor.HttpContext!.Request.GetEncodedUrl())
192192
{
193193
Query = queryStringValue
194194
};
@@ -200,7 +200,7 @@ private string GetLinkForPagination(int pageOffset, string pageSizeValue)
200200
private string GetQueryStringInPaginationLink(int pageOffset, string pageSizeValue)
201201
{
202202
IDictionary<string, string> parameters =
203-
_httpContextAccessor.HttpContext.Request.Query.ToDictionary(pair => pair.Key, pair => pair.Value.ToString());
203+
_httpContextAccessor.HttpContext!.Request.Query.ToDictionary(pair => pair.Key, pair => pair.Value.ToString());
204204

205205
if (pageSizeValue == null)
206206
{
@@ -311,7 +311,7 @@ private IDictionary<string, object> GetRouteValues(string primaryId, string rela
311311
// By default, we copy all route parameters from the *current* endpoint, which helps in case all endpoints have the same
312312
// set of non-standard parameters. There is no way we can know which non-standard parameters a *different* endpoint needs,
313313
// so users must override RenderLinkForAction to supply them, if applicable.
314-
RouteValueDictionary routeValues = _httpContextAccessor.HttpContext.Request.RouteValues;
314+
RouteValueDictionary routeValues = _httpContextAccessor.HttpContext!.Request.RouteValues;
315315

316316
routeValues["id"] = primaryId;
317317
routeValues["relationshipName"] = relationshipName;

src/JsonApiDotNetCore/Serialization/JsonApiReader.cs

+2
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
8181
ValidateRequestBody(model, body, context.HttpContext.Request);
8282
}
8383

84+
// ReSharper disable once AssignNullToNotNullAttribute
85+
// Justification: According to JSON:API we must return 200 OK without a body in some cases.
8486
return await InputFormatterResult.SuccessAsync(model);
8587
}
8688

src/JsonApiDotNetCore/Serialization/RequestDeserializer.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ private OperationKind GetOperationKind(AtomicOperationObject operation)
146146
{
147147
case AtomicOperationCode.Add:
148148
{
149-
if (operation.Ref != null && operation.Ref.Relationship == null)
149+
if (operation.Ref is { Relationship: null })
150150
{
151151
throw new JsonApiSerializationException("The 'ref.relationship' element is required.", null,
152152
atomicOperationIndex: AtomicOperationIndex);
@@ -523,14 +523,14 @@ private bool IsCreatingResource()
523523
{
524524
return _request.Kind == EndpointKind.AtomicOperations
525525
? _request.OperationKind == OperationKind.CreateResource
526-
: _request.Kind == EndpointKind.Primary && _httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method;
526+
: _request.Kind == EndpointKind.Primary && _httpContextAccessor.HttpContext!.Request.Method == HttpMethod.Post.Method;
527527
}
528528

529529
private bool IsUpdatingResource()
530530
{
531531
return _request.Kind == EndpointKind.AtomicOperations
532532
? _request.OperationKind == OperationKind.UpdateResource
533-
: _request.Kind == EndpointKind.Primary && _httpContextAccessor.HttpContext.Request.Method == HttpMethod.Patch.Method;
533+
: _request.Kind == EndpointKind.Primary && _httpContextAccessor.HttpContext!.Request.Method == HttpMethod.Patch.Method;
534534
}
535535
}
536536
}

test/JsonApiDotNetCoreExampleTests/IntegrationTests/ContentNegotiation/ContentTypeHeaderTests.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public async Task Returns_JsonApi_ContentType_header()
3434

3535
// Assert
3636
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
37-
httpResponse.Content.Headers.ContentType.ToString().Should().Be(HeaderConstants.MediaType);
37+
httpResponse.Content.Headers.ContentType.Should().NotBeNull().And.Subject.ToString().Should().Be(HeaderConstants.MediaType);
3838
}
3939

4040
[Fact]
@@ -67,7 +67,7 @@ public async Task Returns_JsonApi_ContentType_header_with_AtomicOperations_exten
6767

6868
// Assert
6969
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
70-
httpResponse.Content.Headers.ContentType.ToString().Should().Be(HeaderConstants.AtomicOperationsMediaType);
70+
httpResponse.Content.Headers.ContentType.Should().NotBeNull().And.Subject.ToString().Should().Be(HeaderConstants.AtomicOperationsMediaType);
7171
}
7272

7373
[Fact]

test/JsonApiDotNetCoreExampleTests/IntegrationTests/Logging/LoggingTests.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public LoggingTests(ExampleIntegrationTestContext<TestableStartup<AuditDbContext
3131
options.ClearProviders();
3232
options.AddProvider(loggerFactory);
3333
options.SetMinimumLevel(LogLevel.Trace);
34-
options.AddFilter((_, __) => true);
34+
options.AddFilter((_, _) => true);
3535
});
3636

3737
testContext.ConfigureServicesBeforeStartup(services =>

test/JsonApiDotNetCoreExampleTests/IntegrationTests/MultiTenancy/RouteTenantProvider.cs

+6-1
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,13 @@ public Guid TenantId
1919
{
2020
get
2121
{
22+
if (_httpContextAccessor.HttpContext == null)
23+
{
24+
throw new InvalidOperationException();
25+
}
26+
2227
string countryCode = (string)_httpContextAccessor.HttpContext.Request.RouteValues["countryCode"];
23-
return TenantRegistry.ContainsKey(countryCode) ? TenantRegistry[countryCode] : Guid.Empty;
28+
return countryCode != null && TenantRegistry.ContainsKey(countryCode) ? TenantRegistry[countryCode] : Guid.Empty;
2429
}
2530
}
2631

test/JsonApiDotNetCoreExampleTests/IntegrationTests/NonJsonApiControllers/NonJsonApiControllerTests.cs

+6-6
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public async Task Get_skips_middleware_and_formatters()
3232

3333
// Assert
3434
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
35-
httpResponse.Content.Headers.ContentType.ToString().Should().Be("application/json; charset=utf-8");
35+
httpResponse.Content.Headers.ContentType.Should().NotBeNull().And.Subject.ToString().Should().Be("application/json; charset=utf-8");
3636

3737
string responseText = await httpResponse.Content.ReadAsStringAsync();
3838
responseText.Should().Be("[\"Welcome!\"]");
@@ -60,7 +60,7 @@ public async Task Post_skips_middleware_and_formatters()
6060

6161
// Assert
6262
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
63-
httpResponse.Content.Headers.ContentType.ToString().Should().Be("text/plain; charset=utf-8");
63+
httpResponse.Content.Headers.ContentType.Should().NotBeNull().And.Subject.ToString().Should().Be("text/plain; charset=utf-8");
6464

6565
string responseText = await httpResponse.Content.ReadAsStringAsync();
6666
responseText.Should().Be("Hello, Jack");
@@ -79,7 +79,7 @@ public async Task Post_skips_error_handler()
7979

8080
// Assert
8181
httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest);
82-
httpResponse.Content.Headers.ContentType.ToString().Should().Be("text/plain; charset=utf-8");
82+
httpResponse.Content.Headers.ContentType.Should().NotBeNull().And.Subject.ToString().Should().Be("text/plain; charset=utf-8");
8383

8484
string responseText = await httpResponse.Content.ReadAsStringAsync();
8585
responseText.Should().Be("Please send your name.");
@@ -107,7 +107,7 @@ public async Task Put_skips_middleware_and_formatters()
107107

108108
// Assert
109109
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
110-
httpResponse.Content.Headers.ContentType.ToString().Should().Be("text/plain; charset=utf-8");
110+
httpResponse.Content.Headers.ContentType.Should().NotBeNull().And.Subject.ToString().Should().Be("text/plain; charset=utf-8");
111111

112112
string responseText = await httpResponse.Content.ReadAsStringAsync();
113113
responseText.Should().Be("Hi, Jane");
@@ -126,7 +126,7 @@ public async Task Patch_skips_middleware_and_formatters()
126126

127127
// Assert
128128
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
129-
httpResponse.Content.Headers.ContentType.ToString().Should().Be("text/plain; charset=utf-8");
129+
httpResponse.Content.Headers.ContentType.Should().NotBeNull().And.Subject.ToString().Should().Be("text/plain; charset=utf-8");
130130

131131
string responseText = await httpResponse.Content.ReadAsStringAsync();
132132
responseText.Should().Be("Good day, Janice");
@@ -145,7 +145,7 @@ public async Task Delete_skips_middleware_and_formatters()
145145

146146
// Assert
147147
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
148-
httpResponse.Content.Headers.ContentType.ToString().Should().Be("text/plain; charset=utf-8");
148+
httpResponse.Content.Headers.ContentType.Should().NotBeNull().And.Subject.ToString().Should().Be("text/plain; charset=utf-8");
149149

150150
string responseText = await httpResponse.Content.ReadAsStringAsync();
151151
responseText.Should().Be("Bye.");

test/JsonApiDotNetCoreExampleTests/IntegrationTests/ResourceConstructorInjection/PostOffice.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public PostOffice(InjectionDbContext injectionDbContext)
3131
private bool IsWithinOperatingHours()
3232
{
3333
DateTimeOffset currentTime = _systemClock.UtcNow;
34-
return currentTime.DayOfWeek >= DayOfWeek.Monday && currentTime.DayOfWeek <= DayOfWeek.Friday && currentTime.Hour >= 9 && currentTime.Hour <= 17;
34+
return currentTime.DayOfWeek is >= DayOfWeek.Monday and <= DayOfWeek.Friday && currentTime.Hour is >= 9 and <= 17;
3535
}
3636
}
3737
}

test/JsonApiDotNetCoreExampleTests/IntegrationTests/Serialization/ETagTests.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
4747
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
4848

4949
httpResponse.Headers.ETag.Should().NotBeNull();
50-
httpResponse.Headers.ETag.IsWeak.Should().BeFalse();
50+
httpResponse.Headers.ETag!.IsWeak.Should().BeFalse();
5151
httpResponse.Headers.ETag.Tag.Should().NotBeNullOrEmpty();
5252

5353
responseDocument.Should().BeEmpty();
@@ -75,7 +75,7 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
7575
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
7676

7777
httpResponse.Headers.ETag.Should().NotBeNull();
78-
httpResponse.Headers.ETag.IsWeak.Should().BeFalse();
78+
httpResponse.Headers.ETag!.IsWeak.Should().BeFalse();
7979
httpResponse.Headers.ETag.Tag.Should().NotBeNullOrEmpty();
8080

8181
responseDocument.Should().NotBeEmpty();
@@ -195,7 +195,7 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
195195

196196
(HttpResponseMessage httpResponse1, _) = await _testContext.ExecuteGetAsync<string>(route);
197197

198-
string responseETag = httpResponse1.Headers.ETag.Tag;
198+
string responseETag = httpResponse1.Headers.ETag!.Tag;
199199

200200
Action<HttpRequestHeaders> setRequestHeaders2 = headers =>
201201
{
@@ -209,7 +209,7 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
209209
httpResponse2.Should().HaveStatusCode(HttpStatusCode.NotModified);
210210

211211
httpResponse2.Headers.ETag.Should().NotBeNull();
212-
httpResponse2.Headers.ETag.IsWeak.Should().BeFalse();
212+
httpResponse2.Headers.ETag!.IsWeak.Should().BeFalse();
213213
httpResponse2.Headers.ETag.Tag.Should().NotBeNullOrEmpty();
214214

215215
responseDocument2.Should().BeEmpty();
@@ -242,7 +242,7 @@ await _testContext.RunOnDatabaseAsync(async dbContext =>
242242
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
243243

244244
httpResponse.Headers.ETag.Should().NotBeNull();
245-
httpResponse.Headers.ETag.IsWeak.Should().BeFalse();
245+
httpResponse.Headers.ETag!.IsWeak.Should().BeFalse();
246246
httpResponse.Headers.ETag.Tag.Should().NotBeNullOrEmpty();
247247

248248
responseDocument.Should().NotBeEmpty();

test/TestBuildingBlocks/FakerContainer.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ private static MethodBase GetTestMethod()
2222
{
2323
var stackTrace = new StackTrace();
2424

25-
MethodBase testMethod = stackTrace.GetFrames().Select(stackFrame => stackFrame?.GetMethod()).FirstOrDefault(IsTestMethod);
25+
MethodBase testMethod = stackTrace.GetFrames().Select(stackFrame => stackFrame.GetMethod()).FirstOrDefault(IsTestMethod);
2626

2727
if (testMethod == null)
2828
{

test/UnitTests/Middleware/JsonApiMiddlewareTests.cs

+7-7
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ private static DefaultHttpContext CreateHttpContext(string path, bool isRelation
159159
ControllerTypeInfo = (TypeInfo)typeof(object)
160160
};
161161

162-
context.SetEndpoint(new Endpoint(null, new EndpointMetadataCollection(controllerActionDescriptor), null));
162+
context.SetEndpoint(new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(controllerActionDescriptor), null));
163163
return context;
164164
}
165165

@@ -192,12 +192,12 @@ private Mock<IResourceGraph> CreateMockResourceGraph(string resourceName, bool i
192192

193193
private sealed class InvokeConfiguration
194194
{
195-
public JsonApiMiddleware MiddleWare { get; set; }
196-
public HttpContext HttpContext { get; set; }
197-
public Mock<IControllerResourceMapping> ControllerResourceMapping { get; set; }
198-
public Mock<IJsonApiOptions> Options { get; set; }
199-
public JsonApiRequest Request { get; set; }
200-
public Mock<IResourceGraph> ResourceGraph { get; set; }
195+
public JsonApiMiddleware MiddleWare { get; init; }
196+
public HttpContext HttpContext { get; init; }
197+
public Mock<IControllerResourceMapping> ControllerResourceMapping { get; init; }
198+
public Mock<IJsonApiOptions> Options { get; init; }
199+
public JsonApiRequest Request { get; init; }
200+
public Mock<IResourceGraph> ResourceGraph { get; init; }
201201
}
202202
}
203203
}

test/UnitTests/Middleware/JsonApiRequestTests.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ private static void SetupRoutes(HttpContext httpContext, string requestMethod, s
112112
ControllerTypeInfo = (TypeInfo)typeof(object)
113113
};
114114

115-
httpContext.SetEndpoint(new Endpoint(null, new EndpointMetadataCollection(controllerActionDescriptor), null));
115+
httpContext.SetEndpoint(new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(controllerActionDescriptor), null));
116116
}
117117
}
118118
}

0 commit comments

Comments
 (0)