.NET Core 从 Razor 页面向控制器发出 AJAX 调用

.NET Core making an AJAX call from a Razor Page to a Controller

我有一个使用 Razor Pages 的 .NET Core 3.1 项目。我从中创建了一个简单的测试,我可以使用以下代码成功进行 Ajax 调用:

Index.cshtml.cs

public class IndexModel : PageModel
{
    public void OnGet()
    {

    }

    public JsonResult OnGetTest()
    {
        return new JsonResult("Ajax Test");
    }
}

Index.cshtml

@page
@model IndexModel

<div class="text-center">
    <p>Click <a href="#" onclick="ajaxTest()">here</a> for ajax test.</p>
</div>

<script type="text/javascript">
    function ajaxTest() {
        $.ajax({
            type: "GET",
            url: "/Index?handler=Test",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (xhr, status, error) {
                console.log(error);
            }
        }).done(function (data) {
            console.log(data);
        });
    }
</script>

但是,我想将 Ajax 方法从 Razor Page 移到 Controller 中,这样我就可以从多个 Razor Pages 中调用它。我使用以下代码创建了一个控制器:

public class AjaxController : Controller
{
    public JsonResult Test()
    {
        return new JsonResult("Ajax Test");
    }
}

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.EnableEndpointRouting = false;
        });
        services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

但是无论我在 url 中为 Ajax 调用使用什么值,我都会得到一个 404 errorControllers 文件夹是否需要在 Pages 目录中?或者我是否需要配置一些路由以将 ControllerRazor Pages 一起使用?

url: "/Ajax/Test" // <-- What goes here?

这是当前的目录结构:

您需要指定一个 Route 属性,如下所示:

[Route("api/Ajax")]
public class AjaxController : Controller
{
    // ...
}

最好用 'Method' 属性装饰每个端点,如下所示:

[HttpGet]
public JsonResult Test()
{
    return new JsonResult("Ajax Test");
}

此外你还需要在Startup.cs中设置正确的配置,如下图,把你没有的部分全部加上:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.EnableEndpointRouting = false;
    });
    services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // lots of stuff...

    // I have this after app.UseStaticFiles(), it may also work elsewhere
    app.UseMvcWithDefaultRoute();

    // lots of other stuff...
}

然后 然后 你应该可以使用路径 /api/Ajax/Test.

来调用它

在 Startup.cs 中,将其添加到 ConfigureServices()

services.AddMvc(options => options.EnableEndpointRouting = false);

在 Startupcs 中,也将此添加到 Configure()

app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

DisplayController.cs

public IActionResult Test()
    {
        return new JsonResult("Hi World");
    }

Index.cshtml

<a onclick="ClickMe();">Click Me</a>
<script>
function ClickMe() {
    $.get("/Display/Test", null, function (e) {
        alert(e);
    });
}
</script>