ASP.NET Web API客户端如何正确处理NotFound响应自定义错误提示
Hey there, let's break down how to fix this issue step by step. The core problem here is twofold: your Web API is returning an HTML error page instead of a clean HTTP status code + structured response, and your client is letting the browser directly handle the API's response instead of processing it programmatically. Here's what you need to do:
1. Fix Your Web API to Return Structured Errors (Not HTML Pages)
First, we need to configure your Web API to send back proper HTTP status codes (like 404 for "not found") along with a JSON/XML response, instead of redirecting to an HTML error page. This way your client can parse the response instead of the browser displaying the API's error page.
For ASP.NET Framework Web API:
Add a custom error handler in your Global.asax.cs and create an error controller to return JSON responses:
// Global.asax.cs protected void Application_Error(object sender, EventArgs e) { var exception = Server.GetLastError(); var httpException = exception as HttpException; Response.Clear(); Server.ClearError(); Response.TrySkipIisCustomErrors = true; // Critical: Bypass IIS's default error pages var routeData = new RouteData(); routeData.Values["controller"] = "Error"; routeData.Values["action"] = "HandleError"; routeData.Values["exception"] = exception; Response.StatusCode = httpException?.GetHttpCode() ?? (int)HttpStatusCode.InternalServerError; IController errorController = new ErrorController(); var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData); errorController.Execute(requestContext); } // ErrorController.cs (in your Web API project) public class ErrorController : ApiController { public HttpResponseMessage HandleError(Exception exception) { var statusCode = exception is HttpException httpEx ? HttpStatusCode.Parse(httpEx.GetHttpCode().ToString()) : HttpStatusCode.InternalServerError; var errorResponse = new { Message = exception.Message, StatusCode = (int)statusCode }; return Request.CreateResponse(statusCode, errorResponse); } }
For ASP.NET Core Web API:
Use a middleware to catch exceptions and return JSON errors:
// Program.cs var builder = WebApplication.CreateBuilder(args); // ... other services ... var app = builder.Build(); // Add this before other middleware like app.UseRouting() app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { context.Response.ContentType = "application/json"; var exceptionFeature = context.Features.Get<IExceptionHandlerPathFeature>(); var statusCode = exceptionFeature?.Error is NotFoundException ? HttpStatusCode.NotFound : HttpStatusCode.InternalServerError; context.Response.StatusCode = (int)statusCode; var errorResponse = new { Message = exceptionFeature?.Error.Message ?? "An unexpected error occurred", StatusCode = (int)statusCode }; await context.Response.WriteAsJsonAsync(errorResponse); }); }); // ... other middleware like app.UseAuthorization(), app.MapControllers() ... app.Run();
Also, make sure you disable any custom IIS error pages that might override your API's responses.
2. Update Your ASP.NET Website Client to Process API Responses Programmatically
You can't just link directly to the API or use a form action pointing to it (that's why the browser shows the API's error page). Instead, use server-side code or AJAX to call the API, check the response status code, and then display your custom error message on your website's page.
Option 1: Server-Side Call (Using HttpClient in .aspx.cs)
In your website's code-behind (e.g., CheckRecord.aspx.cs):
protected void CheckRecordButton_Click(object sender, EventArgs e) { var recordId = RecordIdTextBox.Text.Trim(); var apiBaseUrl = "http://your-api-base-url/"; // Replace with your API's URL using (var client = new HttpClient()) { client.BaseAddress = new Uri(apiBaseUrl); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync($"api/records/{recordId}").Result; if (response.IsSuccessStatusCode) { // Record exists: show success message StatusLabel.Text = "✅ Record exists in the database"; StatusLabel.CssClass = "alert alert-success"; } else if (response.StatusCode == HttpStatusCode.NotFound) { // Record not found: show custom error StatusLabel.Text = "❌ No matching record found. Please verify your input."; StatusLabel.CssClass = "alert alert-danger"; } else { // Other errors: generic message StatusLabel.Text = $"⚠️ Request failed with status: {response.StatusCode}"; StatusLabel.CssClass = "alert alert-warning"; } } }
Option 2: Frontend AJAX Call (jQuery Example)
If you want a smoother, page-refresh-free experience:
<!-- In your .aspx page --> <input type="text" id="recordIdInput" placeholder="Enter record ID"> <button id="checkRecordBtn">Check Record</button> <div id="statusMessage"></div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $('#checkRecordBtn').click(function() { var recordId = $('#recordIdInput').val().trim(); var apiUrl = "http://your-api-base-url/api/records/" + recordId; $.ajax({ url: apiUrl, type: "GET", contentType: "application/json", success: function() { $('#statusMessage').html("✅ Record exists").removeClass().addClass("alert alert-success"); }, error: function(xhr) { if (xhr.status === 404) { $('#statusMessage').html("❌ No matching record found").removeClass().addClass("alert alert-danger"); } else { $('#statusMessage').html(`⚠️ Error: ${xhr.statusText}`).removeClass().addClass("alert alert-warning"); } } }); }); }); </script>
Key Notes
- CORS: If your API and website are on different domains, you'll need to enable CORS in your Web API to allow the client to make requests.
- Avoid Browser Navigation: Never use
<a href="api-url">or<form action="api-url">for API calls meant to be processed by your client code—these will make the browser load the API's response directly.
内容的提问来源于stack exchange,提问作者Arseniy

