在 .NET API 操作过滤器中重定向

dyl*_*ion 5 c# actionfilterattribute asp.net-web-api

我希望能够读取 ActionFilterAttribute 中的请求标头,并指导用户。我还想维护现有的请求,或者将控制器和 URL 参数传递给新的请求。我知道这在 MVC 中很容易,但还没有在 Web API 中完成。

Iva*_* R. 8

其实这很容易。您只需创建HttpResponseMessage对象。

public class RedirectAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
            response.Headers.Location = new Uri("https://www.stackoverflow.com");
            actionContext.Response = response;
        }
    }
Run Code Online (Sandbox Code Playgroud)