简体   繁体   English

是否可以在 asp.net 核心路由中包含应用程序名称?

[英]Is it possible to include the application name in the asp.net core routes?

I have a simple phonebook app that allows the user to search for an employee via a dropdown list of departments or by name via text input.我有一个简单的电话簿应用程序,它允许用户通过部门下拉列表或通过文本输入按姓名搜索员工。 The way I'm handling the search is simply changing the action attribute of the html form with javascript based on whatever they typed or whichever option they selected in the dropdown:我处理搜索的方式只是根据他们键入的内容或他们在下拉菜单中选择的任何选项,用 javascript 更改 html 表单的操作属性:

function selectedOption(option) {
    var selValue = option.value;

    document.getElementById("search-form").action = "/home/index/" + selValue;
}

This works on localhost but when I host it on IIS:这适用于本地主机,但是当我将它托管在 IIS 上时:

machineName/appName

becomes变成

machineName/home/index/selValue

cutting off the app name and returning a 404 error切断应用名称并返回 404 错误

The only way I've been able to get around this is with some hardcoding to check whether "home/index" exists in the path already...我能够解决这个问题的唯一方法是使用一些硬编码来检查路径中是否已经存在“home/index”......

function selectedOption(option) {
    var selValue = option.value;

    if (window.location.href.includes("home")) {
        var searchDest = selValue
    } else {
        var searchDest = window.location.href + "/home/index/" + selValue
    }

    document.getElementById("search-form").action = searchDest;
}

This works but it is not very clean or conventional.这可行,但不是很干净或传统。 Is there some way I can have the app name configured in Startup.cs?有什么方法可以在 Startup.cs 中配置应用程序名称吗? I saw the same issue in another question here but I'm getting syntax errors when I try to add another MapRoute.我在这里的另一个问题中看到了同样的问题,但是当我尝试添加另一个 MapRoute 时出现语法错误。 This is all that I currently have:这就是我目前所拥有的一切:

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

Any idea how to get around this?知道如何解决这个问题吗?

as mentioned above by @Desmond Chin , for cshtml you can use HTML helpers.正如@Desmond Chin上面提到的,对于cshtml ,您可以使用HTML助手。 I think the best one for that case is to use @Url.Action(actionName, controllerName) instead @Url.Content() - which is used for js , css , img , etc..我认为这种情况下最好的方法是使用@Url.Action(actionName, controllerName)而不是@Url.Content() - 它用于jscssimg等。

You can use this code bellow to achieve this:您可以使用下面的代码来实现这一点:

function selectedOption(option) {
    var selValue = option.value;

    document.getElementById("search-form").action = '@Url.Action("Index", "Home")?<<VARIABLENAMEHERE>>'+selValue;

}

The Html Helper will take care of your url, virtual paths and etc Html 助手将照顾您的 url、虚拟路径等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM