What's the best way to communicate between angularjs and mvc5? - asp.net-mvc

I've some confusions to transfer data between angularjs and MVC5. I am creating single page application (SPA).
What is the best way to work with angularjs? Is MVC controllers or MVC APIs ?.
I read it here that api's are good for SPA. So, do I need to build a different project for APIs ?
What about asynchronous communication for Angularjs with MVC ?
I am not getting a right direction to work ahead. I am familiar with mvc but not APIs. So, Please guid me a right way !!
Thanks in advance

First of all, with the current version of Visual Studio (2013) there's no distinction between a "web form" project and an "mvc" project. There's just a web application project and inside you can put whatever you want.
Now from my experience a nice and clean way to approach your problem is to create normal MVC controllers to render the razor views that contain the angularJS application(s), and to create WebAPI controllers for the RESTful interface for the ajax methods.
In angularJS you don't really need to manually do your ajax calls. There is a more convenient and powerful way: resources. They also play well with the WebAPI design, since a WebAPI controller works with a single type of object (i.e. a customer) and through HTTP VERBS allows you to do the CRUD. For instance:
// assume we have a backend repository that handles the data
public HttpResponseMessage Get()
{
return this.Request.CreateResponse(HttpStatusCode.OK, this.repository.GetAllCustomers());
}
public HttpResponseMessage Post(Customer customer)
{
var modifiedCustomer = this.repository.Update(customer);
this.repository.SaveChanges();
return this.Request.CreateResponse(HttpStatusCode.OK, modifiedCustomer);
}
This method queries all the available customers and returns them. You don't define here whether to return JSON or XML: the WebAPI framework reads the HTTP HEADERS of the WebAPI request and serializes the data as requested from the client. For JSON, which you'll be likely be using, it does the serialization through the default JSON serializer defined. You can override this to change the way JSON is created, a common way is to use JSON.NET with custom settings.
AngularJS resources are made to map a single URL and work with all the verbs internally and expose you methods like $save, $query, $get and so forth, so they couple up very well. For instance:
var customerRes = $resource('/customers');
var currentCustomers = customerRes.query(function(){ // query is mapped to the GET verb
currentCustomers[0].email = "foo#baz.bar";
currentCustomers[0].$save(); // default mapped to the POST verb
});
I suggest you to check the documentation and samples for more details.

You can use MVC controller functions with Async and MVC API both. In Controller Async methods you need to handle all responses manually as API have inbuild many features. In controller Async methods your application will handle self calls.
Of course API gives you more flexibility to work on different application types.
More thing you need to worry about when your MVC application have APIs for different type of application likewise mobile apps etc.
1. Pool Services.
2. Threads per worker process in IIS.
These will define scale of your application when you have APIs or Async methods in application for different type of application.

1) You can create Simple Controller - and inside create methods that will return JsonResult
And call thats methods from Angular via AJAX
2) Yes - If you want build API - you need create new project type of WebAPi (right now is v 2.0) - but you can create it in one solution with SPA
3) You can call ajax asynchronous - its not a problem

Related

How do I hardcode a route root for Url.Action when generating a confirmation link

My Asp.net core web app can generate a confirmation link successfully using
string confirmationLink = Url.Action("SetPassword","Account",
new
{
userid = userMaster.Id,
token = confirmationToken
},
protocol: HttpContext.Request.Scheme);
This roots the route using the root of the current controller's page.
Now I have moved out the logic to a web api and I would like to use the root of the calling page in the Url.Action statement in the webapi.
I want to achieve following points.
a) get the root of the current page and
b) having passed that root to the webApi how do I seed Url with it so that it is available to Url.Action?
Workaround: I am generating the confirmation link as a simple string.
string confirmationLink = ${this.config.p_ConfirmationURLRoot}/{this.config.p_ConfirmatonURLController}/{this.config.p_ConfirmationURLAction}?userId={ userMaster.Id}&token={ confirmationToken}";
This does not resolve the questions posed above, but if like me your end goal is a working link that may be used else where, this approach will satisfy that requirement.
It sounds like you're trying to work with request-routing for a front-end application using the routing of a separate API. This isn't a use-case for the ASP.NET routing systems; they are only interested in routes within the application domain. The front-end application has its routes and the API has its routes: both are completely separate concerns.
This is a good model, one you want to work with rather than against. The front-end application should be free to change its URLs without requiring changes in other applications.
By all means, have a separate API to perform logic like user-creation and validation of security tokens, but these are not concerns which should be intermingled with front-end routing.

When Web API 2.0 infrastructure populates Session values?

My Web API (2.0) services and MVC (4.0) code is running inside same web application. I call Web APIs from MVC application as usual HTTP service call.
I have added IAuthenticationFilter in the WebApi pipeline because I want to do some security related validations before any Web Api controller is executed. I keep security related data (E.g. TokenId) in the HttpContext.Current.Session. E.g. HttpContext.Current.Session["TokenId"].
Somehow data kept in the Session is available when I access it from MVC controller or from WebApi controller. But it's NOT available in the AuthenticationFilter when filter runs for the first time i.e. when very first WebApi call is done from MVC application.
Can you tell me when Session is populated by WebApi infrastructure and why values stored in the Session are unavailable during first call ? Note that they are available from the second call onwards!
I have already verified that Session has values in it. Its just that they are not available in the filter during it's first execution.
SessionStateBehavior.Required is already set correctly from WebApi from Global.asax.
(I know that Session is not recommended but I have to use it for now.)
Try with this snippet in global.ascx.cs (mine is in VB but just translate the code)
Protected Sub Application_BeginRequest()
if IsWebApiRequest() Then
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required)
end if
end sub
Private function IsWebApiRequest() as Boolean
return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Contains("api")
end function
For me it works and makes the session available in the AuthenticationFilter

How to secure a JsonResult?

The very first part of this answer on another question explains how an existing MVC site can very quickly have added to it the ability to expose its data (e.g. to a Winforms app requesting the data), all for a couple of lines of code (without having to convert to WCF/Web API and add extra layers - our project is pretty small and basic):
public JsonResult GetCategoryList()
{
var list = //return list
return Json(list, JsonRequestBehavior.AllowGet);
}
So we've tested the above as a quick and easy solution and it's clearly very nearly working because in the stream we get the html source for our MVC app's login.
And indeed if we add the AllowAnonymous annotation we do get the Json stream that we're after.
However we don't want to allow anonymous, we want some protection. Have tried adding:
Dim nc As New NetworkCredential("username", "password")
request.Credentials = nc
just before firing request.GetResponse but that isn't working (this may be completely ignorant but it seemed worth a shot). When I say it isn't working, I mean we go back to getting the login page's html source in the stream.
So how to allow the winforms app to incude some kind of authentication (which will work) with its request for the data? As I say, getting the data is working (proved by AllowAnonymous).
You should separate the authentication code for the web application (the one returning the login) from the one that you are exposing the API.
Looks like you are using forms authentication for the WebSite part and you should keep it that way. However, in the public API GetCategoryList you should either implement a different authentication strategy with ActionFilters for example.

What is the recommended way of sending data from a non web client to a MVC 3 application?

I would like to use a java client to send data to my MVC 3 app. The information will only be a bunch of strings such as a username, password hash, etc.
I was thinking of base64 + url encoding a simple XML structure and send it from my client using a Url to my MVC application like so:
myapp.com/Post/Add/{endcoded string goes here}
This will probably work just fine but what is the best way of passing data into a MVC application?
Thanks.
I would recommend you using standard HTTP protocol stuff. For example a POST verb with content type of application/x-www-form-urlencoded works just great, or you could even use multipart/form-data:
On the ASP.NET MVC side you would have a controller action accepting a view model:
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
...
}
And finally you would write a custom model binder which would read the XML from the request and deserialize it back to your view model.
I would recommend you avoiding custom stuff, wheel and protocol reinvention as much as possible (such as base64 encoding of parameters).
As far as the client side is concerned, my last Java experience is dating back to 2003 so I cannot exactly tell you how to create an HTTP Java client but I am more than persuaded that it should be an easy task.

ASP.NET MVC and Ajax, concurrent requests?

AJAX newbie here!
At the moment in my ASP.NET MVC web app my AJAX requests appear to be getting batched or queued, im not sure.
No requests seem to be getting completed until the previous request has finished.
How do I go about getting the requests to return independantly?
I dont necessarily want someone to give me the answer but maybe some links to good tutorials or resources which could help. Thanks
I'm expanding on Lachlan Roche's answer, which is correct.
The ASP.NET framework will "single-thread" requests that deal with Session scope (a global resource), to prevent one request from interfering with another. In WebForms I think you can use the Page directive to specify that individual pages don't use Session and therefore don't need to treated synchronously like this.
The problem is that in ASP.NET MVC all requests use Session, because it's used to implement TempData. You can disable session state entirely, as Lachlan Roche pointed out, or you can deal with this on a case-by-case basis.
A possible solution might be to kick off your own background threads to process any long-running code, so that the initial request "completes" as quickly as possible.
ASP.NET will serially process requests on a per-session basis unless sessions are configured as disabled or read only in web.config via the enableSessionState attribute on the pages element.
As this is a page setting, this will not affect MVC controllers and they will still be subject to serial request processing.
Curiously, even with sessions disabled or set to readonly, we can still read and write session data. It seems to only affect the session locking that causes serial request processing.
<system.web>
<pages enableSessionState="ReadOnly"/>
</system.web>
Pages can also have an enableSessionState property, though this is not relevant to MVC views.
<%# Page EnableSessionState="True" %>
With the release of ASP.MVC 3 you can now add an attribute to your controllers to mark the Session as readonly, which allows actions to be called concurrently from the same client.
Sessionless Controller Support:
Sessionless Controller is another great new feature in ASP.NET MVC 3. With Sessionless Controller you can easily control your session behavior for controllers. For example, you can make your HomeController's Session as Disabled or ReadOnly, allowing concurrent request execution for single user. For details see Concurrent Requests In ASP.NET MVC and HowTo: Sessionless Controller in MVC3 – what & and why?.
- from this DZone article.
By adding SessionState(SessionStateBehaviour.Disabled) to your controller, the runtime will allow you to invoke multiple actions concurrently from the same browser session.
Unfortunately I don't think there is a way to mark an action so as to only disable the session when that action is called, so if you have a controller that has some actions that require the session and others that do not, you will need to move the ones that do not into a separate controller.
In later versions of ASP MVC you can decorate individual controller classes with the SessionStateAttribute
[System.Web.Mvc.SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class MyController : Controller
{
}
Since .NET Framework v3.0 released, you can use "SessionStateBehavior" enum with SessionStateAttribute:
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class MyController : BaseController { }
Well Concurrent Request are more on browser dependent aswell if you fire suppose 10 concurrent request to an action Using AJax in Mozilla and same using IE 8 then you will find that Mozilla has style to fire one request wait for its response and then fire second and so on... for this is one by one basis whereas in IE * this fire about 6 concurrent request at a time to Server.
So Concurrent Request are also dependent on browser type.
I suggest using jQuery for your ajax needs with asp.net mvc, I have used it exclusively and it has been extremely easy.
As for tutorials I would look at this: http://docs.jquery.com/Ajax
There are tons of options to play with and I also suggest downloading firebug so you can watch requests launch from your page asynchronously and see if they fire and what they return etc.
Like the other guy side, AJAX request are asynchronous and don't get queued up and they all return independently when they finish, so if you watch in firebug it will be easy to see what is going on behind the scenes and before the debugger gets hit

Resources