这可以通过使用代理模式来实现。这是一个简化EnableCorsAttribute
的示例,以显示如何:
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Mvc;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System;
public class EnableCorsAttribute:System.Web.Mvc.ActionFilterAttribute, System.Web.Http.Filters.IActionFilter {
class HttpActionFilter:System.Web.Http.Filters.ActionFilterAttribute {
public override void OnActionExecuted(HttpActionExecutedContext filterContext) {
var res = filterContext.Response;
res.Headers.Add("Access-Control-Allow-Origin", String.Join(",\x20", m_httpFilter.Origins));
res.Headers.Add("Access-Control-Allow-Headers", String.Join(",\x20", m_httpFilter.Headers));
res.Headers.Add("Access-Control-Allow-Credentials", "true");
base.OnActionExecuted(filterContext);
}
public HttpActionFilter(EnableCorsAttribute filter) {
m_httpFilter=filter;
}
EnableCorsAttribute m_httpFilter;
}
public override void OnActionExecuted(ActionExecutedContext filterContext) {
var res = filterContext.HttpContext.Response;
res.Headers.Add("Access-Control-Allow-Origin", String.Join(",\x20", this.Origins));
res.Headers.Add("Access-Control-Allow-Headers", String.Join(",\x20", this.Headers));
res.Headers.Add("Access-Control-Allow-Credentials", "true");
base.OnActionExecuted(filterContext);
}
public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) {
return m_mvcFilter.ExecuteActionFilterAsync(actionContext, cancellationToken, continuation);
}
public EnableCorsAttribute(String origins, String headers, String methods) {
m_mvcFilter=new HttpActionFilter(this);
var separator = new[] { ',' };
var options = StringSplitOptions.RemoveEmptyEntries;
this.Origins=origins.Split(separator, options);
this.Headers=headers.Split(separator, options);
this.Methods=methods.Split(separator, options);
}
public IList<String> Origins {
get; private set;
}
public IList<String> Headers {
get; private set;
}
public IList<String> Methods {
get; private set;
}
System.Web.Http.Filters.IActionFilter m_mvcFilter;
}