Redirecting from an API - asp.net-mvc

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

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!

It depends on what you are doing with said API. You can setup an API to perform purely CRUD operations or you can make your API a lot smarter and say have it serve up actual HTML to be rendered on the client (which is sort of what MVC does) or you can take it a step further and turn it into a Hypermedia service that will define the view as well as the state of your system. The front end is then tasked with simply rendering what is provided by your API.

Related

.NET Core MVC/Azure AD - 302 Found when making an ajax request

I am using Azure AD along with asp.net core mvc. The following code is the same with a default MVC project generated with Work or School Accounts authentication.
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
Everything works just fine for the most time. The app is basically a notepad. A user logs in and adds notes/tasks. Everything after logging in is done using ajax requests. After some time the app stops working because there is a need for authentication again. Note that if I refresh the page everything is working again.
Am I doing this right? Am I missing something or this kind of use case is not supported.
Should I just create a javascript function that will auto refresh the page after some time?
Should I just create a javascript function that will auto refresh the page after some time?
You could try to create a hidden iframe in all the templates used by the Web App to make automatic calls to a MVC controller method that forces a call to renew the authentication data on a regular basis.
This is achieved very easily by configuring an automatic javascript process in the front-end executed in a loop on a regular basis of 45'. This value could be configured or extracted from a configuration file too. The only key condition is that it must be less than one hour.
Here is the simplified example code related to MVC Controller:
/* Action method, inside "Account" controller class, to force renewal of user authentication session */
public void ForceSignIn()
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
And here is the simplified example HTML and javascript code employed to call silently in a hidden iframe to MVC Controller:
<iframe id="renewSession" hidden></iframe>
<script>
setInterval( function ()
{ #if (Request.IsAuthenticated) {
<text>
var renewUrl = "/Account/ForceSignIn";
var element = document.getElementById("renewSession");
element.src = renewUrl;
</text>
}
},
1000*60*45
);
</script>
For more details, you could refer to this article which get the similar situation with you.
I found a simple solution by accident. My goal was to hit a check endpoint every minute and If I get a 302 status code I would redirect the user to the authentication page.
public IActionResult Check()
{
return Ok(new { });
}
I left the developer tools open and noticed that every 30 mins I get a bigger response.
And this actually refreshes the cookie and as a result there is no need to redirect the user.
So to sum up someone needs to do this check every 40-50 minutes because the expiration is set to ~1 hour by default.

TypeScript with Angular.JS and web API

I'm working on an asp.mvc3 web api project. in this project I use TypeScript and Angular.js
and I need to access the business layer from TypeScript through the Web API. I called the Web API inside the constructor method in TypeScript using the
code given below.
constructor($scope, $http: any) {
$scope.VM = this;
$http.get("/API/PrivateAPI/Test/1").success((a) => { this.Tiles = a });
var bb = this.Tiles;
}
However, when trying to get the object list from the business layer, the Tiles array is empty. I debugged the code and found out the Web API is called after passing the last line of the constructor and does return results. I need to call that method inside the constructor and get object list to the Tiles array.
Does anyone know how to do so?
First of, I think you should do the following (notice .data) :
$http.get("/API/PrivateAPI/Test/1").success((response) => { this.Tiles = response.data });
Anyways, $http only supports async http requests. What you want can be done by a synchronous XHR request and that is considered bad UI experience, since the browser window freezes till the XHR request completes, and therefore $http doesn't support it (configuration docs).
What you can do is something like :
call another function from response e.g.
(response) => { this.Tiles = response.data; this.continueWithProcessing(); }
Or, Setup a variable to hide a preloader when the response comes back:
(response) => { this.Tiles = response.data; this.allDone=true; }
Where you have an ng-show on something like:
<div ng-show="!VM.allDone">Loading the data....</div>
Or both :)
Note: An async setting is supported in underlying browsers native XHR object and therefore in $.ajax which is the jquery ajax function : http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings. However it is a horrible UI experience + if you use it from angular you are responsible for scope.apply.

ASP.net MVC SPA routing

I'm planning to build a SPA with asp.net MVC4 but I'm not quite sure how I have to Setup my Project because of the Routing. Most SPA's work with hashrouting like this mypage/#/News/today for instance.
What would happen if the browses directly to mypage/News/today if I haven't specified a Controller named News with an action today?
The App should handle both types of Routing, how can I achieve this?
Do I have to build my App in a classic way, like Adding several Controllers with appropriate Actions and views and also build a clientside MVC structure with knockout, jquery etc?
You'll have to let all routes to "pages" fall through to let your SPA handle them (including essentially fake 404s if it's not to a real page in your SPA), but at the same time, need to make sure that you get the correct responses for API calls and/or file requests.
Below is the setup I have (I am using Vue as the js framework but that doesn't matter much for this, and not at all for the server-side piece).
First, add this to your Startup.cs, in addition to your default route setup:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.Use(async (context, next) =>
{
await next();
var path = context.Request.Path.Value;
// If there's no available file and the request doesn't contain an extension, we're probably trying to access a page
if (context.Response.StatusCode == (int)HttpStatusCode.NotFound && !Path.HasExtension(path) && !path.StartsWith("/api"))
{
context.Request.Path = "/Home/SpaRedirect"; // attempts to redirect to the URL within the SPA
context.Response.StatusCode = (int)HttpStatusCode.OK; // Make sure we update the status code, otherwise it returns 404
await next();
}
});
...
}
So the newly added SpaRedirect to HomeController looks like this, and just stores the requested URL in ViewData...
public IActionResult SpaRedirect()
{
ViewData["RequestUrl"] = HttpContext.Request.Path;
return View("Index");
}
Then in Index.cshtml, just capture that requested url in session storage so we have it available on the client-side:
<script src="~/dist/main.js" asp-append-version="true">
sessionStorage.setItem("redirectAttempt", #ViewData["RequestUrl"]);
</script>
Then in your boot script file (the entry-point for your SPA), add something like:
let redirectAttemptUrl = sessionStorage.getItem("redirectAttempt");
if (redirectAttemptUrl) {
router.push(redirectAttemptUrl);
sessionStorage.removeItem("redirectAttempt");
}
Which just checks for the presence of a requested url, and then the SPA's router attempts to navigate to it (in the example above it is a vue-router), then removes it from storage.
So this way, if a user attempts to navigate directly to a URL by entering it in the url bar (or via a bookmark) the app will load and take them to the right place, IF it exists... which takes us to the last piece...
Finally, you have to handle "404s" within your SPA, which is done by adding a catch-all route to your routes defs that takes user to a 404 component page you set up, which for Vue would look like this:
// adding an explicit 404 path as well for programmatically handling when something is not found within the app, i.e. return this.$router.push('/404')
{ path: '/404', component: NotFound, name: '404', alias: '*' }, // remove alias to not show the actual url that resulted in our little 404 here
{ path: '*', redirect: '/404' }, // this is the catch-all path to take us to our 404 page
Caveat: I'm no expert so could be missing something, would love additional comments on how to improve this. One thing that this doesn't handle is if the user is ALREADY in the SPA and for some reason edits the URL directly to navigate to someplace else, it would still trigger a server call and full reload, which ideally wouldn't be the case, but this is a pretty trivial issue I'd say.

Redirect after EndInvoke in ASP.NET MVC

Hi have the following code on my view (JQuery):
$.post('<%=Url.Content("~/Customer/StartLongRunningProcess")%>');
Wich invokes an asynchronous call (C#):
public void StartLongRunningProcess()
{
ProcessTask processTask = new ProcessTask();
processTask.BeginInvoke(new AsyncCallback(EndLongRunningProcess), processTask);
}
Finally, the result of the call:
public void EndLongRunningProcess(IAsyncResult result)
{
ProcessTask processTask = (ProcessTask)result.AsyncState;
string id = processTask.EndInvoke(result);
RedirectToAction("~/SubscriptionList/SubscribedIndex/" + id);
}
The redirect is ignored. Response.Redirect also fails, since the HTTP headers has been already sent. I've tried change the window.location from javascript, this works, but I'm unable to pass the parameter id by ViewData. Any idea to resolve this?
Are you sure the headers have already been sent? I'm not really up on asynchronous controllers, but I would doubt that it would start sending any headers right away. My first thought would be that a redirect response to an ajax call isn't handled by the browser. You will probably need to implement some logic that sends back a result with the URL and have your success delegate in jQuery look for that piece of data and then do the redirect through javascript (i.e. window.location).
HTH

What is the correct response to an HTTP POST request?

For a POST method, the W3 specs say:
If a resource has been created on the origin server, the response
SHOULD be 201 (Created) and contain an entity which describes the
status of the request and refers to the new resource, and a Location
header (see Section 10.4).
http://www.ietf.org/internet-drafts/draft-ietf-httpbis-p2-semantics-05.txt (section 8.5)
The standard response actually seems to be to send a Redirect to the newly created resource.
I'm building my site with ASP.NET MVC, and tried to follow the spec, so created a ResourceCreatedResult class:
public class ResourceCreatedResult : ActionResult
{
public string Location { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.StatusCode = 201;
context.HttpContext.Response.ClearHeaders();
context.HttpContext.Response.AddHeader("Location", Location);
}
}
And my action looks something like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateNew(string entityStuff)
{
Entity newEntity = new Entity(entityStuff);
IEntityRepository entityRepository = ObjectFactory.GetInstance<IEntityRepository>();
entityRepository.Add(newEntity);
ActionResult result = new ResourceCreatedResult()
{ Location = Url.Action("Show", new { id = newEntity.Id }) };
return result;
}
However, IE, Firefox and Chrome all fail to redirect to the new resource. Have I messed up generating the correct response, or do web browsers not expect this type of response, instead relying on servers to send a Redirect response?
To be explicit, browsers (including modern browsers like Firefox 3 and IE8) do not "take the hint" and follow up an HTTP 201: Created response with a GET request to the URI supplied in the Location header.
If you want browsers to go to the URI supplied in the Location header, you should send an HTTP 303: See Other status instead.
Redirect after post or post/redirect/get is something your application must do to be user friendly.
Edit. This is above and beyond the HTTP specifications. If we simply return a 201 after a POST, the browser back button behaves badly.
Note that Web Services requests (which do NOT respond to a browser) follow the standard completely and do NOT redirect after post.
It works like this.
The browser POSTS the data.
Your application validates the data. If it's invalid, you respond with the form so they can fix it and POST.
Your application responds with a redirect.
The browser gets the redirect and does a GET.
Your application sees the GET and responds.
Now -- hey presto! -- the back button works.
My solution is to respond with a '201 Created' containing a simple page with a link to the new resource, and a javascript redirect using location.replace().
This lets the same code work for API and browser requests, plays nicely with Back and Refresh buttons, and degrades gracefully in old browsers.
As stated in the spec the response SHOULD be a HTTP 201 with redirect. So it isn't mandatory for a browser vendor to implement the correct answer...
You should try to change to a 30x code to see if it is correctly redirected. If so, it's a browser problem, else it may come from your code (I don't know anything in ASP.NET so I can't "validate" your code)
Shouldn't that only count for when something is "Created" and therefore a simple redirect to action should be genuinely sufficient?

Resources