Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting from an API

I am trying to learn/expand my knowledge of .NET MVC/REST/API's and Web-sockets/SignalR. To do this I am implementing a chat app.

I have a typical MVC intro page that gets the users name and email address in a form and that data is submitted to a RESTFul API where the new user is added to the database.

<form class="form-horizontal" role="form" action="/api/GroopsAPIUsers" method="POST">

Inside of the controller for that page(?) I'm redirecting the user to a page where they can select which room they would like to enter.

public HttpResponseMessage  Post( GroopsUser userValue)
{
     userValue.ID =  Guid.NewGuid();
     bool results = groopsRepository.AddNewUser(userValue);
     //   return results;

     var response = Request.CreateResponse(HttpStatusCode.Redirect);

      //from http://stackoverflow.com/questions/11324711/redirect-from-asp-net-web-api-post-action

     string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
     response.Headers.Location = new Uri (fullyQualifiedUrl + "/home/rooms/?userID=" + userValue.ID);

     return response;

}

But this doesn't feel right. It seems like the API should only be doing CRUD operations and shouldn't have anything to do with which page the user is redirected to.

Is this the wrong approach? If so, can someone point me in the right direction? (I'm not sure that I've used all of these terms correctly)

...gregory

like image 916
Gregory Mertens Avatar asked May 22 '26 09:05

Gregory Mertens


1 Answers

I can see why you don't think it feels right. Usually, you would design your Web API in such a way, that it is platform agnostic, so the only thing it cares about is the incoming HTTP requests, and operations based on those. When you redirect a request to another URL, you are designing around the web browser, thus constraining yourself to that one platform. Sometimes that's what you need, sometimes it isn't. (if it indeed is what you need, then you should probably stick to just regular Asp.NET MVC, and not Web Api)

Instead of what you have now, you could make your application more flexible by returning, for example, a 200 status code from your controller, after a successful operation. That way, it is up to the client-side application to decide what to do from there. (This is where you redirect, if your client-side application is browser-based.)

So how exactly do you achieve this with your browser application? You might already have guessed it, but the answer is Javascript. Instead of making a synchronous POST request to your API, via your form, you could make the request async, and then wait for the response from the server. Then you can take an appropriate action, based on what the response contains.

A quick example:

Controller

public HttpResponseMessage  Post(GroopsUser userValue)
{
     userValue.ID =  Guid.NewGuid();
     bool results = groopsRepository.AddNewUser(userValue);

     var response = Request.CreateResponse<GroopsUser>(HttpStatusCode.OK, userValue);

     return response;
}

Form

<form class="form-horizontal" id="group-form" onsubmit="return addToGroup()" role="form" action="/api/GroopsAPIUsers" method="POST">

Javascript (jQuery)

<script>
    function addToGroup()
    {
        $.ajax({
                type: "POST",
                url: $('#group-form').attr('action'),
                data: $('#group-form').serialize(),
                dataType: "json",
                success: function(data) {
                    window.location.replace('/home/rooms/?userID=' + data.ID);
                },
                error: function(){
                      alert('error handing here');
                }
            });
        return false;
    }

</script>

If anything is unclear, or if I'm mistaken about anything, please let me know!

like image 61
Tobias Avatar answered May 25 '26 05:05

Tobias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!