Redirect in a .NET API action filter
Asked Answered
P

1

6

I'd like to be able to read a Request header in an ActionFilterAttribute, and direct the user. I'd also like to maintain the existing Request, or pass the controller and URL params to the new Request. I know this is easy in MVC, but haven't done it in a web API.

Peptize answered 6/7, 2017 at 21:9 Comment(3)
MVC and WebApi are essentially the same thing. If you know how to create a custom attribute in MVC you should be 99% of the way there in WebAPI. Unless I am misunderstanding your questionStepfather
They're not the same thing. The contexts and Requests are different objects, and the redirect actions are different in MVC and web API. Which may all be moot, and you may be correct, if it's as simple matter of calling something like Request.CreateRedirect, or something similar. But I don't know of such a method, that takes url params and HTTP method types.Peptize
Also, to be clear, I know how to create an attribute. It's how to implement the redirect, that I'm not certain of. I know it's kind of dumb and not what RESTful APIs are built to do, but my team lead wants me to redirect to either a sync or an async method, based on a header value. So I need to CreateResponse, I think, but would like to know if there's a simpler redirect, for cleaner reusability.Peptize
C
8

Actually it is very easy. You just create HttpResponseMessage object.

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;
        }
    }
Complacence answered 9/7, 2017 at 17:56 Comment(3)
And then of course, base.onActionExcuting/Async. Exactly what I was looking for; thanks!Peptize
In case anyone else had this problem, you may need using System.Net.Http; for CreateResponse to be available.Pneumato
this response comes back to itself ajax request but i want to redirect to another page..Septavalent

© 2022 - 2024 — McMap. All rights reserved.