333
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
|
||||
namespace SwashbuckleEx.WebApiTest
|
||||
{
|
||||
/// <summary>
|
||||
/// 简单Cors跨域处理器
|
||||
/// </summary>
|
||||
public class SimpleCorsHandler : DelegatingHandler
|
||||
{
|
||||
private const string Origin = "Origin";
|
||||
private const string AccessControlRequestMethod = "Access-Control-Request-Method";
|
||||
private const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
|
||||
private const string AccessControlAllowOrign = "Access-Control-Allow-Origin";
|
||||
private const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
|
||||
private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
|
||||
private const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials";
|
||||
|
||||
private const string AccessControlMaxAge = "Access-Control-Max-Age";
|
||||
// <add name = "Access-Control-Allow-Headers" value="Content-Type" />
|
||||
// <add name = "Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
bool isCrosRequest = request.Headers.Contains(Origin);
|
||||
bool isPrefilightRequest = request.Method == HttpMethod.Options;
|
||||
if (isCrosRequest)
|
||||
{
|
||||
Task<HttpResponseMessage> taskResult = null;
|
||||
if (isPrefilightRequest)
|
||||
{
|
||||
taskResult = Task.Factory.StartNew<HttpResponseMessage>(() =>
|
||||
{
|
||||
HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
|
||||
response.Headers.Add(AccessControlAllowOrign,
|
||||
request.Headers.GetValues(Origin).FirstOrDefault());
|
||||
string method = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
|
||||
//if (method != null)
|
||||
//{
|
||||
// response.Headers.Add(AccessControlAllowMethods, method);
|
||||
//}
|
||||
string headers = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
|
||||
if (!string.IsNullOrWhiteSpace(headers))
|
||||
{
|
||||
response.Headers.Add(AccessControlAllowHeaders, headers);
|
||||
}
|
||||
response.Headers.Add(AccessControlAllowCredentials, "true");
|
||||
response.Headers.Add(AccessControlMaxAge, "1728000");
|
||||
return response;
|
||||
}, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
taskResult = base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
|
||||
{
|
||||
var response = t.Result;
|
||||
response.Headers.Add(AccessControlAllowOrign,
|
||||
request.Headers.GetValues(Origin).FirstOrDefault());
|
||||
response.Headers.Add(AccessControlAllowCredentials, "true");
|
||||
return response;
|
||||
});
|
||||
}
|
||||
return taskResult;
|
||||
}
|
||||
return base.SendAsync(request, cancellationToken);
|
||||
}
|
||||
|
||||
//private const string Origin = "Origin";
|
||||
//private const string AccessControlRequestMethod = "Access-Control-Request-Method";
|
||||
//private const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
|
||||
//private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
|
||||
//private const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
|
||||
//private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
|
||||
|
||||
//// 重写基类的发送消息方法
|
||||
//protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
//{
|
||||
// bool isCrosRequest = request.Headers.Contains(Origin);
|
||||
// bool isPrefilightRequest = request.Method == HttpMethod.Options;
|
||||
// if (isCrosRequest)
|
||||
// {
|
||||
// if (isPrefilightRequest)
|
||||
// {
|
||||
// return Task.Factory.StartNew(() =>
|
||||
// {
|
||||
// var response = new HttpResponseMessage(HttpStatusCode.OK);
|
||||
// response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
|
||||
|
||||
// var currentAccessControlRequestMethod =
|
||||
// request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
|
||||
|
||||
// if (currentAccessControlRequestMethod != null)
|
||||
// {
|
||||
// response.Headers.Add(AccessControlAllowMethods, currentAccessControlRequestMethod);
|
||||
// }
|
||||
|
||||
// var requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
|
||||
// if (!requestedHeaders.IsNullOrEmpty())
|
||||
// {
|
||||
// response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
|
||||
// }
|
||||
// return response;
|
||||
// }, cancellationToken);
|
||||
// }
|
||||
// return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
|
||||
// {
|
||||
// var response = t.Result;
|
||||
// response.Headers.Add(AccessControlAllowOrigin,
|
||||
// request.Headers.GetValues(Origin).FirstOrDefault());
|
||||
// return response;
|
||||
// });
|
||||
// }
|
||||
// return base.SendAsync(request, cancellationToken);
|
||||
//}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using System.Web.Http;
|
||||
using System.Web.Http.Description;
|
||||
using Swashbuckle.Application;
|
||||
using SwashbuckleEx.WebApiTest;
|
||||
using SwashbuckleEx.WebApiTest.Extensions;
|
||||
using SwashbuckleEx.WebApiTest.Selectors;
|
||||
|
||||
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
|
||||
namespace SwashbuckleEx.WebApiTest
|
||||
{
|
||||
public class SwaggerConfig
|
||||
{
|
||||
public static void Register()
|
||||
{
|
||||
var thisAssembly = typeof(SwaggerConfig).Assembly;
|
||||
|
||||
GlobalConfiguration.Configuration
|
||||
.EnableSwagger(c =>
|
||||
{
|
||||
// 配置简单API文档信息-用于单个文档
|
||||
//c.SingleApiVersion("v1", "Test.WebApi").Contact(x =>
|
||||
//{
|
||||
// x.Email("jianxuanhuo1@126.com");
|
||||
// x.Name("jian玄冰");
|
||||
// x.Url("https://www.cnblogs.com/jianxuanbing");
|
||||
//}).TermsOfService("jian玄冰1").License(x =>
|
||||
//{
|
||||
// x.Name("MIT");
|
||||
// x.Url("https://www.cnblogs.com/jianxuanbing");
|
||||
//}).Description("自定义文案内容,可以随便输入内容");
|
||||
c.MultipleApiVersions(ResolveAreasSupportByRouteConstraint, (vc) =>
|
||||
{
|
||||
vc.Version("Admin", "中文后台 API").Description("这个用于测试一下备注信息").TermsOfService("www.baidu.com").License(
|
||||
x =>
|
||||
{
|
||||
x.Name("jian玄冰");
|
||||
x.Url("www.baidu.2333");
|
||||
})
|
||||
.Contact(x =>
|
||||
{
|
||||
x.Name("2017").Email("jianxuanhuo1@126.com").Url("www.baidu.xxxx");
|
||||
});
|
||||
vc.Version("v1", "Common API", true);
|
||||
|
||||
vc.Version("Client", "Client API");
|
||||
});
|
||||
|
||||
c.ApiKey("Authorization").Description("OAuth2 Auth").In("header").Name("Authorization");
|
||||
//c.OAuth2("jwt").AuthorizationUrl("http://localhost:9460/oauth/token")
|
||||
// .TokenUrl("http://localhost:9460/oauth/token").Scopes(
|
||||
// x =>
|
||||
// {
|
||||
// x.Add("scope", "admin");
|
||||
// });
|
||||
c.DocumentFilter<SwaggerAreasSupportDocumentFilter>();
|
||||
|
||||
c.OperationFilter<AddUploadOperationFilter>();
|
||||
|
||||
c.IncludeXmlComments(string.Format("{0}/bin/SwashbuckleEx.WebApiTest.XML", AppDomain.CurrentDomain.BaseDirectory));
|
||||
c.ShowDeveloperInfo();
|
||||
})
|
||||
.EnableSwaggerUi(c =>
|
||||
{
|
||||
c.EnableApiKeySupport("Authorization","header");
|
||||
});
|
||||
}
|
||||
|
||||
private static bool ResolveAreasSupportByRouteConstraint(ApiDescription apiDescription, string targetApiVersion)
|
||||
{
|
||||
if (targetApiVersion == "v1")
|
||||
{
|
||||
return apiDescription.Route.RouteTemplate.StartsWith("api/{controller}");
|
||||
}
|
||||
var routeTemplateStart = "api/" + targetApiVersion;
|
||||
return apiDescription.Route.RouteTemplate.StartsWith(routeTemplateStart);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web.Http;
|
||||
using System.Web.Http.Dispatcher;
|
||||
using SwashbuckleEx.WebApiTest.Selectors;
|
||||
|
||||
namespace SwashbuckleEx.WebApiTest
|
||||
{
|
||||
public static class WebApiConfig
|
||||
{
|
||||
public static void Register(HttpConfiguration config)
|
||||
{
|
||||
// Web API 配置和服务
|
||||
config.Services.Replace(typeof(IHttpControllerSelector),new NamespaceHttpControllerSelector(config));
|
||||
// Web API 路由
|
||||
config.MapHttpAttributeRoutes();
|
||||
|
||||
config.Routes.MapHttpRoute(
|
||||
name: "AdminApi",
|
||||
routeTemplate: "api/Admin/{controller}/{action}/{id}",
|
||||
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional, namespaces = new string[] { "SwashbuckleEx.WebApiTest.Areas.Admin.Controllers" } });
|
||||
config.Routes.MapHttpRoute(
|
||||
name: "ClientApi",
|
||||
routeTemplate: "api/Client/{controller}/{action}/{id}",
|
||||
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional, namespaces = new string[] { "SwashbuckleEx.WebApiTest.Areas.Client.Controllers" } });
|
||||
|
||||
config.Routes.MapHttpRoute(
|
||||
name: "CommonApi",
|
||||
routeTemplate: "api/{controller}/{action}/{id}",
|
||||
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional, namespaces = new string[] { "SwashbuckleEx.WebApiTest.Controllers" } }
|
||||
);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user