我按照以下步骤在我的控制器中启用CORS:
- 安装了nuget包:
安装包Microsoft.AspNet.WebApi.Cors
- 在Global.asax中,添加以下行:
GlobalConfiguration.Configure(WebApiConfig.Register);
- 在WebApiConfig Register方法中,具有以下代码:
public static void Register(HttpConfiguration config) {
config.EnableCors();
config.MapHttpAttributeRoutes();
}
- 在web.config中,以下处理程序必须是管道中的第一个处理程序:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
- 在从ApiController派生的控制器中,添加EnableCorsAttribute:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MyController : ApiController
我使用以下jquery调用Api
$.ajax({
type: 'GET',
url: getURL,
dataType: 'json'
})
.done(
function (data, textStatus, jqXHR) {
$("#" + elementId).text(jqXHR.responseText || data);
}
)
.fail(
function (jqXHR, textStatus, errorThrown) {
$("#" + elementId).text(textStatus);
}
);
当我运行这些步骤时,我得到所请求资源上的“No'Access-Control-Allow-Origin'标头 . ”例外 .
如果我只在web.config中启用它:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
它工作正常,但它会影响我的所有应用程序操作 .
我怎么能把它限制在只有我的控制器?我在这里错过了什么让它起作用吗?
提前致谢 .