是否可以在React应用程序中使用.NET Core Controller的重定向(301)?

时间:2017-12-15 02:00:02

标签: asp.net asp.net-mvc reactjs

我正在使用.NET EF Core + React-Redux项目,我们目前正在使用.NET控制器登录(使用Razor / MVC作为登录/注册页面)。登录后,用户将使用React组件路由到页面。

我试图使用.NET控制器注销,但是当我点击注销链接时,它只会带我到404错误页面。我尝试过使用post方法的表单和按钮,以及一个锚标记(但是锚标记没有指定方法)。我也试过让表单调用onSubmit函数,但是函数调用给了我一个400错误。

是否可以使用Controller从基于React的页面注销?

帐户/ AccountController.cs:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout()
{
    Console.WriteLine("Logging out...");
    await _signInManager.SignOutAsync();
    logger.LogInformation("User logged out.");
    return RedirectToAction("Index", "Home");
}

React Component:/Navbar.js(使用Controller):

import React from 'react';

export default class Navbar extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <form action="/Account/Logout" method="post>
                <button type="submit">Logout</button>
            </form>
        )
    }
}

React Component:/Navbar.js(使用axios / API调用服务器):

import React from 'react';
import axios from 'axios';

export default class Navbar extends React.Component {
    constructor(props) {
        super(props);
    }

    logoutUser() {
        axios.post('/Account/Logout');
    }

    render() {
        return (
            <form onSubmit={this.logoutUser}>
                <button type="submit">Logout</button>
            </form>
        )
    }
}

404错误:

This is the error from server: Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)

Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
            app.UseDatabaseErrorPage();
            app.UseStatusCodePages();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true,
                ReactHotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseAuthentication();

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

            //routes.MapSpaFallbackRoute(
            //    name: "spa-fallback",
            //    defaults: new { controller = "Home", action = "Index" });
        //});
    }

0 个答案:

没有答案