105 lines
3.2 KiB
C#
105 lines
3.2 KiB
C#
// RevitHttpControl/Startup.cs
|
||
using System.Web.Http;
|
||
using System.Web.Http.Cors;
|
||
using Newtonsoft.Json;
|
||
using Newtonsoft.Json.Serialization;
|
||
using Owin;
|
||
|
||
namespace RevitHttpControl
|
||
{
|
||
/// <summary>
|
||
/// OWIN 启动配置类
|
||
/// </summary>
|
||
public class Startup
|
||
{
|
||
/// <summary>
|
||
/// 配置 OWIN 应用程序
|
||
/// </summary>
|
||
/// <param name="app">应用程序构建器</param>
|
||
public void Configuration(IAppBuilder app)
|
||
{
|
||
var config = new HttpConfiguration();
|
||
|
||
// 配置跨域
|
||
ConfigureCors(config);
|
||
|
||
// 配置路由
|
||
ConfigureRoutes(config);
|
||
|
||
// 配置JSON序列化
|
||
ConfigureJsonSerialization(config);
|
||
|
||
// 配置错误处理
|
||
ConfigureErrorHandling(config);
|
||
|
||
// 应用配置
|
||
app.UseWebApi(config);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 配置跨域支持
|
||
/// </summary>
|
||
/// <param name="config">HTTP配置</param>
|
||
private void ConfigureCors(HttpConfiguration config)
|
||
{
|
||
// 启用CORS,允许所有来源、方法和头部
|
||
var cors = new EnableCorsAttribute("*", "*", "*");
|
||
config.EnableCors(cors);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 配置路由
|
||
/// </summary>
|
||
/// <param name="config">HTTP配置</param>
|
||
private void ConfigureRoutes(HttpConfiguration config)
|
||
{
|
||
// 启用属性路由
|
||
config.MapHttpAttributeRoutes();
|
||
|
||
// 配置默认路由(作为备用)
|
||
config.Routes.MapHttpRoute(
|
||
name: "DefaultApi",
|
||
routeTemplate: "api/{controller}/{id}",
|
||
defaults: new { id = RouteParameter.Optional }
|
||
);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 配置JSON序列化设置
|
||
/// </summary>
|
||
/// <param name="config">HTTP配置</param>
|
||
private void ConfigureJsonSerialization(HttpConfiguration config)
|
||
{
|
||
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
|
||
|
||
// 使用驼峰命名
|
||
jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
|
||
|
||
// 忽略空值
|
||
jsonSettings.NullValueHandling = NullValueHandling.Ignore;
|
||
|
||
// 缩进格式化(开发环境友好)
|
||
jsonSettings.Formatting = Formatting.Indented;
|
||
|
||
// 日期格式
|
||
jsonSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
|
||
jsonSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
|
||
|
||
// 枚举序列化为字符串
|
||
jsonSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
|
||
|
||
// 移除XML格式化器,只保留JSON
|
||
config.Formatters.Remove(config.Formatters.XmlFormatter);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 配置基础错误处理
|
||
/// </summary>
|
||
/// <param name="config">HTTP配置</param>
|
||
private void ConfigureErrorHandling(HttpConfiguration config)
|
||
{
|
||
// 包含错误详细信息(开发环境)
|
||
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly;
|
||
}
|
||
}
|
||
} |