-
Notifications
You must be signed in to change notification settings - Fork 99
/
server_aspnet.html
61 lines (47 loc) · 2.4 KB
/
server_aspnet.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
---
layout: default
title: enable cross-origin resource sharing
---
<div class="container">
<section>
<h1>CORS on ASP.NET</h1>
<p>
If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:
</p>
<pre class="code">Response.AppendHeader("Access-Control-Allow-Origin", "*");</pre>
<p class="note">
Note: this approach is compatible with IIS6, IIS7 Classic Mode, and IIS7 Integrated Mode.
</p>
<h2>ASP.NET Web API</h2>
<p>ASP.NET Web API 2 supports CORS.</p>
<p>To enable CORS support, add the <a href="http://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors">Microsoft.AspNet.WebApi.Cors</a> NuGet package to your project.</p>
<p>Add this code to your configuration:</p>
<pre class="code">
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
}
</pre>
<p>To enable cross-origin requests, add the [EnableCors] attribute to your Web API controller or controller method:</p>
<pre class="code">
[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
</pre>
<h3>Enabling Globally</h3>
<p>The method described above can also be used to enable CORS across the API without annotating each controller:</p>
<pre class="code">
public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("http://example.com", "*", "*");
config.EnableCors(corsAttr);
}
</pre>
<p>For more information, see the official <a href="http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api">Web API documentation</a>.</p>
<h2>Libraries</h2>
<ul><li>The open source Thinktecture.IdentityModel security library contains a full-featured CORS implementation. Here is the <a href="http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/">announcement page</a> with some samples. Here is the source for <a href="https://github.com/thinktecture/Thinktecture.IdentityModel.45">.NET 4.5</a> and for <a href="https://github.com/thinktecture/Thinktecture.IdentityModel.40">.NET 4.0</a>. Both are packaged into a <a href="http://nuget.org/packages/Thinktecture.IdentityModel">Nuget package</a> downloadable from Visual Studio.</li></ul>
</section>
</div>