如何使用MVC 3启用/使用跨源资源共享?

时间:2021-01-07 04:12:37

I want to submit a form using AJAX to a MVC 3 Controller.

我想使用AJAX将表单提交给MVC 3 Controller。

The form and the controller are on two different domains, which is why i want to use CORS.

表单和控制器位于两个不同的域上,这就是我想使用CORS的原因。

I have read that the following code should do the trick in ASP.NET:

我已经读过以下代码应该在ASP.NET中执行操作:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

from http://enable-cors.org/#how-asp.net

Should this code go directly in the controller that takes the form data? As far as i know, there has to be some exchange of data between the client posting data and the server, to determine wether CORS is enabled/supported or not, so i figure that the one line of code has to go somewhere else?

该代码应该直接在采用表单数据的控制器中吗?据我所知,客户端发布数据和服务器之间必须进行一些数据交换,以确定是否启用/支持更好的CORS,所以我认为一行代码必须去其他地方?

Thanks

1 个解决方案

#1


3  

This could go in the controller. Actually I would probably externalize it in a custom action filter to avoid repeating it in every controller action that needs to be invoked from a cross domain AJAX call. There are no additional steps necessary. Just make sure that your browser supports CORS because if it doesn't adding this line will have strictly no effect whatsoever.

这可以进入控制器。实际上我可能会在自定义动作过滤器中将其外化,以避免在需要从跨域AJAX调用中调用的每个控制器动作中重复它。没有必要的额外步骤。只需确保您的浏览器支持CORS,因为如果它不添加此行将完全没有任何影响。

#1


3  

This could go in the controller. Actually I would probably externalize it in a custom action filter to avoid repeating it in every controller action that needs to be invoked from a cross domain AJAX call. There are no additional steps necessary. Just make sure that your browser supports CORS because if it doesn't adding this line will have strictly no effect whatsoever.

这可以进入控制器。实际上我可能会在自定义动作过滤器中将其外化,以避免在需要从跨域AJAX调用中调用的每个控制器动作中重复它。没有必要的额外步骤。只需确保您的浏览器支持CORS,因为如果它不添加此行将完全没有任何影响。