[Analyzer] Prefer HttpRequest.ReadFormAsync over HttpRequest.Form
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
## Background and Motivation
`HttpRequest.Form` is a blocking API (it reads the request body which may not be available yet). Using it can cause thread exhaustion and server throughput problems.
`HttpRequest.Form` is confusing to people as similar APIs such `HttpRequest.QueryString`, `HttpRequest.Cookies`, `HttpRequest.Headers`, etc, are safe to use.
## Proposed Analyzer
### Analyzer Behavior and Message
Using `HttpRequest.Form` should generate a warning. There are some cases where it is safe to use, so we need to figure out how broad to make the warning.
One option could be:
* API used inside an async method = warning
* API used inside a sync method = info
See discussion at https://github.com/dotnet/aspnetcore/issues/44390#issuecomment-1269279517 for more info.
### Category
- [ ] Design
- [ ] Documentation
- [ ] Globalization
- [ ] Interoperability
- [ ] Maintainability
- [ ] Naming
- [x] Performance
- [ ] Reliability
- [ ] Security
- [ ] Style
- [ ] Usage
### Severity Level
- [ ] Error
- [x] Warning (async method?)
- [x] Info (sync method?)
- [ ] Hidden
## Usage Scenarios
```csharp
public Task SaveProduct()
{
var productName = Request.Form["product_name"]; // WARNING HERE
_repository.Add(new Product { Name = productName });
await _repository.SaveAsync();
return SuccessResult();
}
```
## Risks
`HttpRequest.Form` is safe if the form has already been loaded. People who know and rely on that behavior and like the terseness of `HttpRequest.Form` would be impacted. They could either suppress the analyzer or assign the form to a local variable:
```csharp
public Task SaveProduct()
{
var form = Request.ReadFormAsync();
var productName = form["product_name"];
var productPrice = form["product_price"];
// etc
}
```
Contributor guide
Assessment
This issue has not been assessed yet.