Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable CORS only for a given route (page) in ASP.NET Razor Pages?

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...

like image 542
g.pickardou Avatar asked Nov 19 '25 05:11

g.pickardou


1 Answers

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

enter image description here

2)Applied the [EnableCors] attribute to MyPageModel

enter image description here

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).

like image 186
Fei Han Avatar answered Nov 21 '25 09:11

Fei Han