【问题标题】:ActionFilterAttribute on Web api call does not correctly redirect to the new locationWeb api 调用上的 ActionFilterAttribute 未正确重定向到新位置
【发布时间】:2017-07-04 15:02:06
【问题描述】:

我的操作过滤器属性没有重定向到我定义的新网址:

public class RunOnServerAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public ServerType Type;

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
    {
        switch (Type)
        {
            case ServerType.CMS:
                if (!filterContext.Request.RequestUri.AbsoluteUri.StartsWith(Config.CMSUrl))
                {
                    Uri correctedUri = new Uri($"{Config.CMSUrl.TrimEnd('/')}/{filterContext.Request.RequestUri.PathAndQuery.TrimStart('/')}");
                    var response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.Moved);
                    response.Headers.Location = correctedUri;
                    return;
                    // This does not seem to work
                }

                break;
        }

        base.OnActionExecuting(filterContext);
    }
}

它只是继续正常的请求。我正在通过检查正在执行的 api 方法中的 Request.RequestUri 来调试它

【问题讨论】:

    标签: c# actionfilterattribute


    【解决方案1】:

    很抱歉没有注意到它是一个 WebAPI 项目。 编写响应应该是一个快速的解决方案。

    var res = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
    res.Headers.Location = new Uri("https://www.google.com");
    actionContext.Response = res;
    

    ------------- 上面更新了。 --------------

    您应该使用 filterContext.Result 并分配 ActionResult。就像你在正常动作中所做的那样。 例如,

    var controller = (YourBaseControllerType)filterContext.Controller;
    filterContext.Result = controller.RedirectToAction("actionName", "controllerName");
    

    filterContext.Result = new RedirectResult(YourUrl);
    

    【讨论】:

    • 这不适用于 API 请求
    • 我应该在设置响应后返回吗?还是我应该继续通过 base.OnActionExecuting 运行 filtercontext?
    • 嗯,这取决于您的要求。但是如果你只是想重定向,那么不调用基地就可以了。
    【解决方案2】:

    OnActionExecuting 在控制器动作方法调用之前被调用,所以在运行过滤器方法之后控制器动作替换响应。我认为OnActionExecuted 方法更适合您的代码。

    【讨论】:

    • 执行意味着它已经在控制器中针对错误的 api url 运行代码
    • 您不需要将正确的 url 返回给客户端,而是在您的应用程序中调用另一个控制器操作吗?
    猜你喜欢
    • 2019-12-15
    • 1970-01-01
    • 2013-08-11
    • 2013-01-05
    • 2013-10-05
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多