ASP.NET Core路由前缀

时间:2019-06-06 08:17:24

标签: c# .net asp.net-core routing

我正在开发ASP.NET Core应用程序。我的应用程序托管在网址为http://somedomain.com/MyApplication的NGinx上。

我需要将所有请求路由到前缀/MyApplication

我的控制器操作响应问题重定向到somedomain.com,而不是somedomain.com/MyApplication

是否可以将路由配置为使用前缀/MyApplication

UPD:例如

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> Login(string returnUrl = null)
        {
            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }

重定向到somedomain.com,但我需要somedomain.com/MyApplication

5 个答案:

答案 0 :(得分:17)

您可以像这样在PathBase之前使用Mvc中间件:

partial class Startup {

    public void Configure(
        IApplicationBuilder app,
        IHostingEnvironment env
    ) {
        app.UsePathBase(new PathString("/MyApplication"));
        app.UseMvc();
    }

}

使用PathBase中间件,无需更改任何mvc代码,它将自动添加到请求和响应中。

请参考https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.usepathbaseextensions.usepathbase?view=aspnetcore-2.2

答案 1 :(得分:4)

[Route("MyApplication")]
public class MyController : Controller
{
    [HttpGet]
    public async Task<IActionResult> Login(string returnUrl = null)
    {
        // Blah!
    }
}

答案 2 :(得分:3)

如果使用的是MVC,则可以尝试更改默认路由格式。 在Startup.cs中替换行

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

与此:

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

让我知道您是否需要

答案 3 :(得分:0)

在App_Start / RouteConfig.cs中:

routes.MapRoute(
    name: "default",
    url: "MyApplication/{controller}/{action}/{id}",
    defaults: new
    {
        controller = "Home",
        action = "Index",
        id = UrlParameter.Optional
    }
);

答案 4 :(得分:0)

ASP.NET Core的属性路由。在下面的示例中显示

[Route("MyApplication")]
public class MyController : Controller
{
    //You can have multiple routes on an action
    [Route("")] /MyApplication
    [Route("/test")] you have move to the /MyApplication/test 
    [HttpGet]
    public async Task<IActionResult> Login(string returnUrl = null)
    {
        //Your Code Session
    }
}

或者您使用 具有Http [Verb]属性的属性路由。 如果是[HttpPost(“ Your Path”)],则在[HttpGet(“ Your Path”)]中添加路径。

[HttpGet("/MyApplication")]
        [AllowAnonymous]
        public async Task<IActionResult> Login(string returnUrl = null)
        {
            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }