谈谈如何在ASP.NET Core中实现CORS跨域(2)

//[EnableCors("AllowSpecificOrigin")] [Route("api/[controller]")] public class HomeAPIController : Controller { [EnableCors("AllowSpecificOrigin")] [HttpGet] public string Get() { return "this message is from another origin"; } [DisableCors] [HttpPost] public string Post() { return "this method can't cross origin"; } }

[EnableCors("AllowSpecificOrigin")] 既为在本 controller 或 action 中应用哪个分组策略。

[DisableCors] 则为本controller或action不允许跨域资源请求

改造浏览器端html

修改localhost网站的index.html,内容应为:

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> </head> <body> <script> $.get("http://localhost:1661/API/HomeAPI", {}, function (data) { alert(data); }, "text"); </script> </body> </html>

调试

F5调试服务端项目,你会看到一个404页面,因为默认路径上没有页面,不用管它,浏览, js会Get请求:1661/API/HomeAPI,并弹出返回值,而如果你去Post请求:1661/API/HomeAPI, 则请求会被拦截。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjywjf.html