ASP.NET MVC 当前请求 url(ajax 调用问题)

use*_*616 2 asp.net ajax asp.net-mvc

我使用流行的技术“ReturnUrl”。我将当前页面的 url 传递给服务器,做一些工作,然后我将用户重定向回这个 url。例如,用户发表评论,然后返回到这个 url。

@using (Html.BeginForm("AddUserComment", "Home", new { returnUrl = HttpContext.Current.Request.RawUrl }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
}
Run Code Online (Sandbox Code Playgroud)

但是,当我通过 ajax 调用加载此表单时,如下所示:

$.ajax({
        type: 'GET',
        url: '/Home/ShowUserCommentsBlock/',
        data: { entityType: entityType, entityId: entityId },
        cache: false,
        ...
    });
Run Code Online (Sandbox Code Playgroud)

HttpContext.Current.Request.RawUrl返回 ajax 请求 url "/Home/ShowUserCommentsBlock?entityType=...",但我需要当前页面 url,其中调用 ajax 请求。我应该用什么代替HttpContext对象?

use*_*616 5

好的,我明白了。我们可以对 ajax 请求使用Request.UrlReferrer属性来检索正确的 url,如下所示:

public ActionResult MyActionMethod()
{
            if (Request.IsAjaxRequest())
                ViewBag.ReturnUrl = HttpContext.Request.UrlReferrer.LocalPath;
            else
                ViewBag.ReturnUrl = HttpContext.Request.RawUrl;

            return View();
}
Run Code Online (Sandbox Code Playgroud)