c # WebApi solve the problem of cross-domain: Cors
WebApi Related Articles:
- C # to build a simple Web API project
- C # WebApi routing configuration
- c # WebApi solve the problem of cross-domain: Cors
- c # WebApi of authentication: Basic Fundamentals Certification
- c # WebApi return type of the interface Detailed
What is cross-domain issue
For security reasons, the browser will limit cross-site request script initiated browsers require JavaScript or Cookie can only access the content under the same domain. For this reason, data access between our different sites will be rejected.
Cors solve cross-domain problems
Cross-Origin Resource Sharing (CORS) mechanism allows Web application server domain access control, so that the cross-domain data transmission to ensure the safe conduct. It solves the problem of cross-domain principle is to tell the browser by adding the appropriate identification to http request packets and response packets inside the domain of which it can request access.
Examples of cross-domain problem solving
Here is write a simple example to illustrate how to use CORS to solve cross-domain
1, create a test project
1.1, two new ASP.NET Web application as a Web site and WebApi site:
1.2, configuration WebApi site
in WebApiConfig.cs configuration file inside the Web API routing, point to concrete action
//Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi1",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
A new test method in the controller, for requesting data:
[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
/// <summary>
/// 得到所有数据
/// </summary>
/// <returns>返回数据</returns>
[HttpGet]
public string GetAllData()
{
return "Success";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
Start Web API project site port number: 8476
1.3, configure the Web site
to create a new index test page:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
测试结果:
<div id="div_test">
hello world
</div>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
public ActionResult Index()
{
return View();
}
- 1
- 2
- 3
- 4
Jquery ajax with the processing request:
<script>
var ApiUrl = "http://localhost:8476/";
$(function () {
$.ajax({
type: "get",
dataType:"json",
url: ApiUrl + "api/Account/GetAllData",
data: {},
success: function (data, status) {
if (data == "success") {
$("#div_test").html(data);
}
},
error: function (e) {
$("#div_test").html("Error");
},
complete: function () {
}
});
});
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
2, the test
In the case of no treatment, and run a Web project, the result is:
You can see your browser to refuse our cross-domain access.
3, using cross-domain CORS
First install CORS, use Nuget search "microsoft.aspnet.webapi.cors" project in WebApiCors above, install the first
when we install this package, the existing packages directory will add two names were "Microsoft.AspNet. Cors.5.2.3 "and" Microsoft.AspNet.WebApi.Cors.5.2.3 ", a reference for the two assemblies stored therein (System.Web.Cors.dll and System.Web.Http.Cors.dll) of It is automatically added to the project WebApiCors
Then clip in App_Start cross-domain configuration folder following WebApiConfig.cs file
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//跨域配置
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi1",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
We tentative three "*" No, of course, when used in the project in general need to specify which domain can cross-domain, cross-domain action what so on. The following describes
Rerun:
Google
IE7, IE8, IE9
I have set up cross-domain Yeah, how IE7,8,9 or not? This time it is necessary to talk about the CORS browser supports problem. Everywhere online search to this picture:
You can see only part of IE8,9 browser support, then how to solve the problem IE browser support it, in fact specified in the call at jQuery.support.cors = true; this one will be able to solve the problem IE8,9:
<script>
jQuery.support.cors = true;
var ApiUrl = "http://localhost:8476/";
$(function () {
$.ajax({
type: "get",
url: ApiUrl + "api/Account/GetAllData",
data: {},
success: function (data, status) {
if (status == "success") {
$("#div_test").html(data);
}
},
error: function (e) {
$("#div_test").html("Error");
},
complete: function () {
}
});
});
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
4, CORS specific parameter settings.
We use the above: config.EnableCors (new new EnableCorsAttribute ( " ", " ", "*")) ;, where the asterisk that as long as people know your url, any resource requests are returned, it is not safe , so the need for access control.
A configuration
in Web.Config configuration:
<appSettings>
<add key="cors:allowedMethods" value="*"/>
<add key="cors:allowedOrigin" value="http://localhost:8610"/>
<add key="cors:allowedHeaders" value="*"/>
</appSettings>
- 1
- 2
- 3
- 4
- 5
Then WebApiConfig.cs configuration file
public static void Register(HttpConfiguration config)
{
//跨域配置
var allowedMethods = ConfigurationManager.AppSettings["cors:allowedMethods"];
var allowedOrigin = ConfigurationManager.AppSettings["cors:allowedOrigin"];
var allowedHeaders = ConfigurationManager.AppSettings["cors:allowedHeaders"];
var geduCors = new EnableCorsAttribute(allowedOrigin, allowedHeaders, allowedMethods)
{
SupportsCredentials = true
};
config.EnableCors(geduCors);
//config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Configuration Method Two
If you just want to do cross-domain for some of api, properties can be directly used to mark a class above the API.
[EnableCors(origins: "http://localhost:8610/", headers: "*", methods: "GET,POST,PUT,DELETE")]
public class AccountController : ApiController
{
/// <summary>
/// 得到所有数据
/// </summary>
/// <returns>返回数据</returns>
[HttpGet]
public string GetAllData()
{
return "Success";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13