Cross Origin Resource Sharing is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. This topic shows how to enable CORS in your ASP.NET MVC 6 application. (For background on CORS, see How CORS works.)
Add the CORS package
In your project.json file, add the following: "dependencies": {
"Microsoft.AspNet.Cors": "6.0.0-beta8"
},
Configure CORS
To configure CORS, callAddCors
in the ConfigureServices
method of your Startup
class, as shown here:public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCors(options =>
{
// Define one or more CORS policies
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder.WithOrigins("http://example.com");
});
});
}
CorsPolicyBuilder
object. To learn more about the various CORS policy settings, see CORS policy options.Apply CORS Policies
The next step is to apply the policies. You can apply a CORS policy per action, per controller, or globally for all controllers in your application.Per action
Add the[EnableCors]
attribute to the action. Specify the policy name.public class HomeController : Controller
{
[EnableCors("AllowSpecificOrigin")]
public IActionResult Index()
{
return View();
}
Per controller
Add the[EnableCors]
attribute to the controller class. Specify the policy name.[EnableCors("AllowSpecificOrigin")]
public class HomeController : Controller
{
Globally
Add theCorsAuthorizationFilterFactory
filter to the global filter collection:public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
}
Disable CORS
To disable CORS for a controller or action, use the[DisableCors]
attribute. [DisableCors]
public IActionResult About()
{
return View();
}
No comments:
Post a Comment