Files
2026-05-29 10:07:05 +08:00

77 lines
2.6 KiB
C#

using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.SelfHost;
namespace MesWork
{
public class WebApi
{
HttpSelfHostConfiguration config = null;
HttpSelfHostServer server = null;
public void InitWebApi()
{
string Url_WebApi = System.Configuration.ConfigurationManager.AppSettings["Url_WebApi"];
InitWebApi(Url_WebApi);
//config = new HttpSelfHostConfiguration(Url_WebApi);
//var json = config.Formatters.JsonFormatter;
//// 解决json序列化时的循环引用问题
//json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
//// 移除XML序列化器
//config.Formatters.Remove(config.Formatters.XmlFormatter);
//// 设置序列化方式为驼峰命名法
//var jsonFormatter = config.Formatters.OfType<System.Net.Http.Formatting.JsonMediaTypeFormatter>().First();
//jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//config.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
//server = new HttpSelfHostServer(config);
//server.OpenAsync().Wait();
}
public void InitWebApi(string url)
{
config = new HttpSelfHostConfiguration(url);
// 跨域设置
config.EnableCors();
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
var json = config.Formatters.JsonFormatter;
// 解决json序列化时的循环引用问题
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
// 移除XML序列化器
config.Formatters.Remove(config.Formatters.XmlFormatter);
// 设置序列化方式为驼峰命名法
var jsonFormatter = config.Formatters.OfType<System.Net.Http.Formatting.JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
}
}
}