尝试在ASP.Net MVC网站中启用CORS时出错

时间:2016-04-12 02:42:35

标签: c# asp.net-mvc cors same-origin-policy

我正在尝试在我的ASP.Net MVC网站中启用CORS。我一直在使用的参考链接here

我下载了CORS的nuget包,并对我的代码应用了以下更改。

我将CORS模块添加到Web.Config,如下所示:

<system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <!---CORS-->
    <modules runAllManagedModulesForAllRequests="true">
      <add name="MvcCorsHttpModule"
         type="Thinktecture.IdentityModel.Http.Cors.Mvc.MvcCorsHttpModule"/>
    </modules>
    <!---CORS-->
    <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>
</system.webServer>

在global.asax.cs中,我补充说:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    //--CORS
    RegisterCors(MvcCorsConfiguration.Configuration);
}

private void RegisterCors(MvcCorsConfiguration corsConfig)
{
    var corsAttr = new EnableCorsAttribute("https://www.youtube.com", "*", "*");
    corsConfig.EnableCors();

}
//xxCORS

但我收到MvcCorsConfiguration的错误:

  

当前上下文中不存在名称“MvcCorsConfiguration”。

我是否需要添加命名空间?请帮忙!

1 个答案:

答案 0 :(得分:0)

如果你想向你的mvc应用程序发出跨域ajax请求,那么只有你需要启用CORS.But如果你正在从你的mvc应用程序向其他网址发出跨域ajax请求,那么你就不会#39 ; t需要在你的mvc应用程序中启用CORS。只测试了这个场景。创建了一个示例mvc应用程序,然后向http://jsonplaceholder.typicode.com/posts/1 url发出了ajax请求,它工作正常。 一种解决方案是,将您的逻辑移至web api并启用CORS,然后从您的mvc或任何其他应用程序调用此URL

相关问题