Nuget 載入 Microsoft.AspNet.WebApi.Cors
Enable CORS
全域
區域
Controller
Action
Disable CORS
區域
Controller
Action
Custom Handle
Add CorsHandle.cs
public class CorsHandle : Attribute, ICorsPolicyProvider
{
private CorsPolicy corsPolicy;
public CorsHandle()
{
this.corsPolicy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true
};
this.corsPolicy.Origins.Add("http://localhost");
this.corsPolicy.Origins.Add("http://www.google.com");
}
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
=> Task.FromResult(this.corsPolicy);
}
Add CorsOnActionHandle.cs
public class CorsOnActionHandle : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
List<string> allowDomain = new List<string>()
{
"http://localhost",
"http://www.google.com"
};
string origin = actionContext.Request.Headers.GetValues("Origin").FirstOrDefault();
bool isAllow = allowDomain.Contains(origin);
if (!isAllow)
{
UnauthorizedObject result = new UnauthorizedObject()
{
code = "401",
message = "domain is not allow"
};
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, result);
}
}
public class UnauthorizedObject
{
public string code { get; set; }
public string message { get; set; }
}
}
近期评论