Html.BeginForm路由到网络API(Html.BeginForm routing to W

2019-09-02 18:20发布

我试图让我的网页发布到我的Web API控制器,而不是我的领域/控制器/动作。 这是我到目前为止,我一直在使用这两种Html.BeginForm和Ajax.Begin形式的尝试:

@using (Ajax.BeginForm("", "", null, new AjaxOptions { HttpMethod = "POST", Url = "api/Standing" }, new { id = "frmStandingAdd", name = "frmStandingAdd" }))

@using (Html.BeginForm("", "api/Standing", FormMethod.Post, new { id = "frmStandingAdd", name = "frmStandingAdd" }))

但我不能让任何张贴到根即http://domain/api/Standing ,而不是两个岗位的区域,即http://domain/Areaname/api/Standing 。 我如何得到它正确地张贴?

更新:这里是我对相关区域路线:

public override string AreaName
{
    get
    {
        return "Areaname";
    }
}

public override void RegisterArea(AreaRegistrationContext context)
{
    string defaultLocale = "en-US";

    context.MapRoute(
        "Areaname_default",
        "{languageCode}/Areaname/{controller}/{action}/{id}",
        new { languageCode = defaultLocale, controller = "Main", action = "Index", id = UrlParameter.Optional });

    context.MapRoute(
        "History",
        "{languageCode}/Areaname/{controller}/{action}/{year}",
        new { controller = "History", action = "Season", year = UrlParameter.Optional });
}

而我的Web API路线:

config.Routes.MapHttpRoute(
    "DefaultApi",
    "api/{controller}/{id}",
    new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
    "DefaultApiWithAction",
    "api/{controller}/{action}/{season}",
    new { id = RouteParameter.Optional }
);

Answer 1:

你可以明确地告诉链接通过包括首张斜线张贴到根目录:

@using (Ajax.BeginForm("", "", null, new AjaxOptions { HttpMethod = "POST", Url = "/api/Standing" }, new { id = "frmStandingAdd", name = "frmStandingAdd" }))

@using (Html.BeginForm("", "/api/Standing", FormMethod.Post, new { id = "frmStandingAdd", name = "frmStandingAdd" }))


Answer 2:

您将需要使用BeginRouteForm为纽带代的Web API的路线总是取决于路径名。 另外,还要确保提供所谓的路线值httproute如下。

@using (Html.BeginRouteForm("DefaultApi", new { controller="Entries", httproute="true" }))


文章来源: Html.BeginForm routing to Web Api