Asp.net Core Minimal Web Api : Redirect to url showing json response

Hamed Vaziri 136 Reputation points
2022-09-05T08:34:03.367+00:00

Hello everyone
in my asp.net core 6.0 minimal web api, i want to have a api method that redirect to a url instead of display anyThing. see my method :

app.MapGet("/", (LinkGeneratorContext db) =>  
{  
    RedirectResult redirect = new RedirectResult("http://www.cnn.com", true);  
    return redirect;  
});  

But this code display json result in my browser & does not redirect to url!
Does something wrong?
Any help can greatly appreciated.
Thanks

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2024-01-24T17:44:42.1833333+00:00
    app.MapGet("/", async context =>
    {    
        await context.Response.Redirect("http://www.cnn.com");
    });
    
    1 person found this answer helpful.
    0 comments No comments

  2. Hamed Vaziri 136 Reputation points
    2022-09-05T15:58:05.097+00:00

    Hi again
    I've solved the problem!
    Try using response.Redirect method (Inject HttpResponse object into your api method via DI).
    I'm developing a short link generator with a single service (link generator). i want to create another service which redirect to orginal link when call from browser get request.
    Thanks

    0 comments No comments

  3. AgaveJoe 26,191 Reputation points
    2024-01-24T17:54:19.8666667+00:00

    the webapi system can host a swagger endpoint. instead of having to write /swagger, I'd like to simply redirect to the swagger page.

    If I understand correctly, you want to display the swagger doc when using a browser and accessing the application root.

    Create an MVC controller where the route in the root and redirect to swagger.

        public class HomeController : Controller
        {
            [Route(""), HttpGet]
            [ApiExplorerSettings(IgnoreApi = true)]
            public RedirectResult Index()
            {
                return Redirect("/swagger/");
            }
        }
    
    0 comments No comments