Di Web.API , atribut ini dapat ditambahkan menggunakan Microsoft.AspNet.WebApi.Cors
seperti yang dijelaskan di http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Di MVC Anda dapat membuat atribut filter untuk melakukan pekerjaan ini untuk Anda:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
AllowMultiple = true, Inherited = true)]
public class EnableCorsAttribute : FilterAttribute, IActionFilter {
private const string IncomingOriginHeader = "Origin";
private const string OutgoingOriginHeader = "Access-Control-Allow-Origin";
private const string OutgoingMethodsHeader = "Access-Control-Allow-Methods";
private const string OutgoingAgeHeader = "Access-Control-Max-Age";
public void OnActionExecuted(ActionExecutedContext filterContext) {
// Do nothing
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
var isLocal = filterContext.HttpContext.Request.IsLocal;
var originHeader =
filterContext.HttpContext.Request.Headers.Get(IncomingOriginHeader);
var response = filterContext.HttpContext.Response;
if (!String.IsNullOrWhiteSpace(originHeader) &&
(isLocal || IsAllowedOrigin(originHeader))) {
response.AddHeader(OutgoingOriginHeader, originHeader);
response.AddHeader(OutgoingMethodsHeader, "GET,POST,OPTIONS");
response.AddHeader(OutgoingAgeHeader, "3600");
}
}
protected bool IsAllowedOrigin(string origin) {
// ** replace with your own logic to check the origin header
return true;
}
}
Kemudian aktifkan untuk tindakan / pengontrol tertentu:
[EnableCors]
public class SecurityController : Controller {
// *snip*
[EnableCors]
public ActionResult SignIn(Guid key, string email, string password) {
Atau tambahkan untuk semua pengontrol di Global.asax.cs
protected void Application_Start() {
// *Snip* any existing code
// Register global filter
GlobalFilters.Filters.Add(new EnableCorsAttribute());
RegisterGlobalFilters(GlobalFilters.Filters);
// *snip* existing code
}