Context
I've successfully enabled CORS for all of my routes in startup and it works:
services.AddCors(options =>
{
options.AddPolicy("MyAllowPolicy",
builder =>
{
builder.WithOrigins("https://www.sample.hostname.com")
.AllowAnyMethod()
.AllowAnyMethod();
});
});
// ...
app.UseCors("MyAllowPolicy");
Question
I would like to be as less relax security as possible, so I would like to allow CORS only a specific page, which is in /Pages/MyFolder/MyPage, and accessible in the route /MyFolder/MyPage
If it would be an ASP.NET Core MVC web application I would use the [EnableCors("MyAllowPolicy")] either on the Controller class or the Action method. However this is a ASP.NET Core 3.1 Pages Web Application.
How can I enable my CORS policy only for /Pages/MyFolder/MyPage?
What I've tried so far:
Everywhere I look only find this sample:
app.UseCors(); // void parameter
//...
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/MyFolder/MyPage",
context => context.Response.WriteAsync("hello"))
.RequireCors("MyAllowPolicy");
endpoints.MapControllers()
.RequireCors("MyAllowPolicy");
endpoints.MapRazorPages();
});
but this obviously renders the response "echo" instead of my page content...
How can I enable my CORS policy only for /Pages/MyFolder/MyPage?
You can apply the [EnableCors] attribute to a Razor Page PageModel to enable CORS for specific handler method(s) that you define within that specific PageModel class, like below.
<script>
$(function () {
$.ajax({
type: "POST",
url: "https://xxx/MyFolder/MyPage?handler=ShowMes",
contentType: "application/json",
data: JSON.stringify("hello world"),
success: function (data) {
console.log(data);
}
});
})
</script>
Handler method
[EnableCors("MyAllowPolicy")]
public class MyPageModel : PageModel
{
public void OnGet()
{
}
public ActionResult OnPostShowMes([FromBody]string mes)
{
//code logic here
return Content($"You sent '{mes}'");
}
}
Test Result
1)Not enable CORS

2)Applied the [EnableCors] attribute to MyPageModel

Besides, please note Anti-forgery token validation would cause the ajax request fails, to make ajax request you sent work well, you can disable Anti-forgery token validation (for testing purpose).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With