# Validation और Error Responses — .NET Core: वेब API बनाएँ, टेस्ट करें और शिप करें

Source: https://www.geekswithgeeks.com/hi/dotnet-core/sec-validation-errors

> ग़लत input को 400 से अस्वीकार करें और एक-सा ProblemDetails error लौटाएँ।

## Input पर भरोसा नहीं

हर request body को अविश्वसनीय मानें। ज़रूरी fields और ranges जाँचें, और साफ़ संदेश के साथ `400 Bad Request` लौटाएँ। `ProblemDetails` (RFC 9457) errors का मानक JSON रूप है, ताकि clients उन्हें एक-सा parse कर सकें।

## जाँचें, सुरक्षित करें, प्रमाणित करें

ग़लत input अस्वीकार होता है, सुरक्षित routes पहचान जाँचते हैं, और tests व्यवहार प्रमाणित करते हैं।

![चार चरण: validate, authenticate, authorize, test।](assets/figures/dotnet-core/section-7-map.svg) — चित्र 7.1 — Validate, authenticate, authorize, test।

## Manual validation और global handler

`Results.ValidationProblem` field errors के साथ 400 लौटाता है। `AddProblemDetails` और `UseExceptionHandler` unhandled exceptions को बिना stack trace के सुरक्षित 500 response में बदलते हैं।

```csharp
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();

app.MapPost("/books", (Book b) =>
{
    var errors = new Dictionary<string, string[]>();
    if (string.IsNullOrWhiteSpace(b.Title)) errors["title"] = ["Title is required."];
    if (b.Price < 0) errors["price"] = ["Price cannot be negative."];
    return errors.Count > 0 ? Results.ValidationProblem(errors) : Results.Ok(b);
});
```

## अंदरूनी जानकारी लीक न करें

Exception text, SQL या file paths नहीं, बल्कि मित्रवत संदेश और correlation ID लौटाएँ। विवरण server पर log करें जहाँ हमलावर उन्हें पढ़ न सकें।

**Quiz:** "आपके JSON में एक अमान्य field है" के लिए कौन-सा status code सही है?

- [ ] 500 Internal Server Error
- [ ] 200 OK
- [x] 400 Bad Request
- [ ] 301 Moved Permanently

*Answer:* 400 Bad Request. 400 का मतलब है कि client ने कुछ अमान्य भेजा। 500 server की ग़लती के लिए है।
