public static class WebApiConfig
{
public static void Register(HttpConfiguration config, bool enableDiagnostics = true)
{
config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
if (enableDiagnostics)
EnableSystemDiagnosticTracing(config);
ConfigureCors(config);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
private static void ConfigureCors(HttpConfiguration config)
{
var origins = new string[]
{
"http://localhost:20936",
"http://msft-web-dev1:93"
};
var corsAttribute = new EnableCorsAttribute(
string.Join(",", origins),
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
"GET, POST, PUT, DELETE, OPTIONS");
corsAttribute.SupportsCredentials = true;
config.EnableCors(corsAttribute);
}
我也尝试过使用*通配符来表示方法和动词。以下是预先发出的OPTIONS请求的响应标头:
您会注意到它没有写出传递预检所需的合适标题。
请求标题:
我的web.config中没有关于auth的具体内容,除了以下内容:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules runAllManagedModulesForAllRequests="true">
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
</modules>
</system.webServer>
我找到了一种方法,可以在global.aspx.cs文件中完成这项工作:
protected void Application_EndRequest()
{
if (Context.Request.HttpMethod == "OPTIONS")
{
Context.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:20936");
Context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
Context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
Context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT, DELETE");
Context.Response.StatusCode = 200;
}
}
当我这样做时,这是我的OPTIONS请求的响应:
我并不是完全反对这条路线,但是EnableCors不是要避免这种情况并且能够全局,每个控制器或每个路由提供这种能力吗?
此外,API托管在IIS(Windows Server 2012)上,它使用Windows身份验证,并禁用包括匿名在内的所有其他方案。
真的难倒在这里。