69 lines
2.0 KiB
C#
69 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Formatting;
|
|
using System.Net.Http.Headers;
|
|
using System.Web.Http;
|
|
using System.Web.Http.Cors;
|
|
using System.Web.Http.SelfHost;
|
|
|
|
namespace WebApi
|
|
{
|
|
|
|
|
|
public class InitServer
|
|
{
|
|
HttpSelfHostConfiguration config = null;
|
|
HttpSelfHostServer server = null;
|
|
public InitServer(string Url_WebApi)
|
|
{
|
|
// var Url_WebApi = System.Configuration.ConfigurationManager.AppSettings["Url_WebApi"];
|
|
Init(Url_WebApi);
|
|
}
|
|
public void Init(string url)
|
|
{
|
|
config = new HttpSelfHostConfiguration(url);
|
|
|
|
// 启用跨域
|
|
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
|
|
// 启用特性路由
|
|
config.MapHttpAttributeRoutes();
|
|
|
|
//config.Routes.MapHttpRoute(
|
|
// name: "DefaultApi",
|
|
// routeTemplate: "api/{controller}/{id}",
|
|
// defaults: new { id = RouteParameter.Optional }
|
|
//);
|
|
|
|
// 自定义路由匹配到action
|
|
config.Routes.MapHttpRoute(
|
|
name: "API Default",
|
|
routeTemplate: "api/{controller}/{action}/{id}",
|
|
defaults: new { id = RouteParameter.Optional }
|
|
);
|
|
|
|
|
|
|
|
server = new HttpSelfHostServer(config);
|
|
|
|
server.OpenAsync().Wait();
|
|
|
|
|
|
}
|
|
public class JsonContentNegotiator : IContentNegotiator
|
|
{
|
|
private readonly JsonMediaTypeFormatter _jsonFormatter;
|
|
|
|
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
|
|
{
|
|
_jsonFormatter = formatter;
|
|
}
|
|
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
|
|
{
|
|
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
|
|
return result;
|
|
}
|
|
}
|
|
}
|
|
}
|