WCF Web API是微软在WCF框架上构建的RESTful服务开发扩展,而WebHttpBinding是WCF中专门用于HTTP通信的绑定类型。
WCF Web API优势:
WebHttpBinding优势:
问题现象:客户端无法正确接收期望的内容类型(JSON/XML)
原因:未正确配置WebHttpBinding或未设置WebGet/WebInvoke的ResponseFormat
解决方案:
// WebHttpBinding配置示例
var binding = new WebHttpBinding {
ContentTypeMapper = new JsonContentTypeMapper()
};
// 服务操作配置
[OperationContract]
[WebGet(UriTemplate = "/data/{id}", ResponseFormat = WebMessageFormat.Json)]
public Data GetData(string id) { ... }
// 自定义内容类型映射器
public class JsonContentTypeMapper : WebContentTypeMapper {
public override WebContentFormat GetMessageFormatForContentType(string contentType) {
return WebContentFormat.Json;
}
}
问题现象:浏览器客户端无法跨域访问服务
原因:WCF默认不支持CORS
解决方案:
// 启用CORS的EndpointBehavior
public class CorsEnabledBehavior : WebHttpBehavior {
protected override IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint) {
var formatter = base.GetRequestDispatchFormatter(operationDescription, endpoint);
return new CorsEnabledFormatter(formatter);
}
}
// 或在web.config中配置
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
问题现象:多个操作匹配同一URI模板
原因:WCF Web API或WebHttpBinding的路由配置不明确
解决方案:
// WCF Web API路由配置示例
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// WebHttpBinding服务配置明确URI模板
[OperationContract]
[WebGet(UriTemplate = "/orders/{orderId}")]
public Order GetOrderById(string orderId) { ... }
[OperationContract]
[WebGet(UriTemplate = "/orders/customer/{customerId}")]
public List<Order> GetOrdersByCustomer(string customerId) { ... }
虽然WCF Web API和WebHttpBinding仍有使用,但微软已推出更现代的替代方案:
这些新技术提供了更好的性能、更简单的编程模型和更活跃的社区支持。
没有搜到相关的文章