.NET Framework 3.5项目REST服务开发:HttpResponseMessage找不到求助
Hey there, let's break down why you're hitting this issue and how to fix it:
Why HttpResponseMessage is missing
HttpResponseMessage is a type introduced with ASP.NET Web API, which only became available starting from .NET Framework 4.0. Since your project is targeting .NET 3.5 and using Visual Studio 2008, this type doesn't exist in your runtime environment—so the compiler can't find it.
Fix 1: Stick with .NET 3.5 WCF REST (Recommended for your current setup)
Since you're already using WCF to expose REST services in .NET 3.5, you don't need HttpResponseMessage to handle responses. Instead, use WCF's built-in WebOperationContext to control response details like status codes, headers, and error messages, while keeping your existing approach of returning strongly-typed objects (which WCF will auto-serialize to JSON as you've configured).
Here's how to adjust your service method to handle errors or custom responses:
using System.ServiceModel.Web; // Make sure you have this namespace referenced public Products getProducts(int producerID) { try { // Your existing logic to fetch products var products = FetchProductsByProducerId(producerID); if (products == null || products.Items.Count == 0) { // Set 404 status if no products found WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; WebOperationContext.Current.OutgoingResponse.StatusDescription = "No products found for the given producer ID"; return new Products(); // Return empty object or null as needed } return products; } catch (Exception ex) { // Handle unexpected errors with 500 status WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError; WebOperationContext.Current.OutgoingResponse.StatusDescription = "An error occurred while retrieving products"; return null; } }
Key notes for this approach:
- Ensure your project has a reference to the
System.ServiceModel.Webassembly (right-click project → Add Reference → .NET tab → select it). - Your existing
[WebInvoke]attribute configuration (ResponseFormat = WebMessageFormat.Json) will still work to serialize yourProductsobject to JSON automatically.
Fix 2: Upgrade to .NET Framework 4.0+ (If possible)
If you're open to updating your development environment and project:
- Upgrade Visual Studio to 2010 or later (since VS2008 doesn't support .NET 4.0+).
- Retarget your project to .NET Framework 4.0 or higher.
- You can then migrate to ASP.NET Web API, which natively uses
HttpResponseMessagefor flexible response control.
However, this is a bigger change and may require refactoring your existing service code.
内容的提问来源于stack exchange,提问作者user2086641

