I am new to MVC and Web Services.
According to my project, I have to show listing data at ViewLayer.
The listing data which I have to show will come from other region via its web service server.
It means that I have to communicate with these web server which is separate with my web application server.
Moreover, my web application have to update some of the data and send this updated data to there web service server again.
That is my project requirement.
So I have searched every possible solutions. Then I found one at stackoverflow.com. According to this, I found that I need to use $.ajax { url: ... } style which I think I need to fully rely on view layer.
Then I had found another solutions which I think I need to fully rely on Controller Layer. I mean I have to write all the code which need to talke with web services only at controller layer.
As I am junior to MVC, I could not decide which one is suitable for me.
Every suggestion will be really appreciated and welcome your any suitable solutions more.
As with all things development - it depends!
If you own the services, they hang off of the same domain, and you're mostly focused on rendering the results of the web service call to HTML, the client-side AJAX calls work well.
If they're on a different domain (or even subdomain), or you want to do more than "just call" the service (e.g., clean up the response, add some tracking, transform it in some way) then handling the web service call via the controller is probably the way to go. You can also easily add server-side caching and logging with this option.
You could use the Unobtrusive Ajax Helpers in MVC3
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-ajax.html
Related
I have MVC application in which the controller sends out emails based on trigger actions on the view. This works correctly. The project also has a business layer dll which is use to interact with the SQL server database. This works correctly. It is now come to my attention that a website under construction needs to access the controller dll to send emails. Right now the website only works with the BLL. With the data objects being different between the website an the application, how do utilize the same code so that both projects can send emails? I am using Razor templates to create the emails, if that makes a difference.
Upgrade to at least MVC 4 and start utilizing the Web API capability to offer a web service to the other application in development.
Here is a good starting blog post
I have a silverlight application which accesses its data through RIA Services, from a WCF app in the server. The current structure looks like this:
DataWebServer - A Web application project, which holds the .aspx page that will call the Silverlight components, the .edmx model file and a MyService class, inheriting from LinqToEntitiesDomainService<FortWayneDB>.
Silverlight App - Contains .xaml e .cs files that will generate the .xap binary files, hosted by the WebServer. It access "DatawebServer" project through RIA Services.
It's all working fine, but now I need to create a new application, and since we will going to need it to run on platforms like tablets and smartphones, we decided to build it in HTML5, instead of Silverlight.
How can I make this new WebApp to access the data entities on "DataWebServer" project?
I think of 3 different solutions, but I'd prefer the third one, which exactly my question.
I could place the new WebApp in a folder in the same webprojeect "DataWebServer", but that wouldn't be very organized, I'd rather separate this app from the "DataWebServer".
The second alternative, which I will follow in case I can't succeed with the third, is to create WebMethods in "DataWebServer" to be accessed from my new WebApp.
the third, which I don't know how to do, is to make my new Web App to access the Entities through RIA Services, in the same way the Silverlight Client does. I've searched the Internet, but all articles I've found show how to access RIA Services from the same project. Does anyone know how I can do that?
The first method is the most sensible.
From your details, I assume the DataWebServer is "publicly" accessible; at least as much as your WebApp would be. There is little value in having WebApp data requests go to a different server, DataWebServer, as this introduces an unnecessary delay while one web server calls another. Instead of re-using the HTTP services from DataWebServer, add the WebApp functionality to the DataWebServer and re-use the LinqToEntities context.
If you desperately want the third option, you should consider creating your WebApp in a way that the JavaScript in the app calls the DataWebServer for data from the client's browser. Importantly, this approach avoids WebApp web server calling to DataWebServer for data.
I'm just starting a project where I would like to use Kendo UI (based on jquery) with C#. A few weeks ago I was successful in handling requests using Web Services (asmx), was pleased with the results and performance, and was able to create forms quickly.
Since this is a new project, I thought I could look into different concepts such as MVC and WebApi. I found MVC to be the most complicaded so I went for WebApi and started playing with controllers and requests. So far what I'm finding (don't judge me, I'm new to these new concepts), is that Web Service seems to be simpler and more flexible.
So I guess what I'm looking for is... what are the main advantages of using MVC vs WebApi and even vs Web Services. Are there any downsides to Web Services? Would it be a bad practice to have my data layer controlled by Entity Framework, all models defined, and my requests handled by Web Services?
Any clarifications are welcome. Thank you.
In a broader sense, Web API is used to create Web Services ! It uses HTTP as its standard for creating services (instead of SOAP like in asmx) as its more open and any type of client like a mobile app, desktop app, web app etc will understand HTTP protocol. Another advantage is that u can easily use JavaScript/jQuery to communicate with your Web API. With SOAP web services, its a nightmare!
Kendo UI and Web API is a great combination. We have recently created a mobile iPad app using this combination and it worked like a charm. We also used Entity Framework with oracle as back end DB and it never gave any issues.
Webservices are nice if you have the need for it. A need as in needing that logic/data in more than one different type of application (such as web, and a mobile app, and a desktop app). (Or if you want to sell the service you're providing)
Using a webservice for ONLY a website which you don't except to expand to other things is complete overkill.
Furthermore, the MVC framework and the Web Api framework are pretty similar except web api is used exclusively for webservices. Coding in both of them will be the difference between white bread and wheat bread.
After searching the entire day about what I should use, I'm not sure what option would be best for my needs so I hope someone with more experience could help me out.
I have a winforms application (c#) and a ASP.NET MVC 4 web application (c#).
I wish to connect these, the goal is to send and receive data from the database which I use in the MVC 4 project, but from within the windows forms application. The data I send from the windows forms application to the database, is then used by the MVC 4 web application.
I am entirely new to web services / Web Api's so I can't really decide what option would be best. Any help would be much appreciated..
If you already created MVC4 project then you can add actions to any controller
and return JSON data like below :
public JsonResult GetCategoryList()
{
var list = //return list
return Json(list, JsonRequestBehavior.AllowGet);
}
or you can create new project of MVC4 and select WEBAPI template . It will create webapi project for you .It will create with example .so it will easy for to create webapi.In webapi it return data automatically convert to xml and json as per request
The WCF Web API abstractions map to ASP.NET Web API roughly as follows
WCF Web AP -> ASP.NET Web API
Service -> Web API controller
Operation -> Action
Service contract -> Not applicable
Endpoint -> Not applicable
URI templates -> ASP.NET Routing
Message handlers -> Same
Formatters -> Same
Operation handlers -> Filters, model binders
Other Links
If you have an MVC 4 App already, it would be better to use Web API (RESTful service)
I assume you have some knowledge in building REST API (understanding of POST, PUT, UPDATE stuff)
It is simple in configuration and usage. All what you need actually is to create a new controller like:
class MyApiController: ApiController {
public Post(SomeClass item) {
....connect to db and do whatever you need with the data
}
}
You'll also should configure routing for Api.
And then in your winForms app you can simply use HttpClient class to perform api call.
HttpClient aClient = new HttpClient();
// Uri is where we are posting to:
Uri theUri = new Uri("https://mysite.com/api/MyApi");
// use the Http client to POST some content ( ‘theContent’ not yet defined).
aClient.PostAsync(theUri, new SomeClass());
Take a look at some implementation details right here:
Web Api Getting Started
Get started with WCF is not so easy as with Web API.
Given the tags you've used, my guess is that you're deciding between SOAP Web Services and WCF. Given these two, I say to go WCF. SOAP web services (as implemented in Visual Studio) are the older technology; still serviceable, but WCF can do everything an older SOAP service can do (including look exactly like a SOAP service) and more.
If you have a web service that connects your web server to your database server (these two things should be on different machines; your web server is exposed to the world by necessity, while your DB server should be locked down like Fort Knox), I see no reason why you shouldn't use that same service as-is for an internal WinForms application (using a LAN/VPN to access the service layer on the DB server). For a WinForms application that must access the data over the Internet, I would recommend reimplementing the service as a WCF service supporting secure encrypted data transfer. You can also set up the service endpoint to only accept HTTPS connections, and thus simply run your existing service through SSL/TLS.
What you choose will primarily depend on how much time-resources you can commit to resolving the problem; moving to HTTPS is a fast fix requiring little if any code changes, while reimplementing in WCF will take more time but will allow additional security measures beyond a simple secure tunnel.
Or something lightweight like Nancy: http://nancyfx.org/
We had some issues with MVC4 WebApi stuff and ended up using ServiceStack on the server side JavaScript/AJAX for web clients and RestSharp for thick clients.
One of our specific issues was the inability to auto generate documentation, significant performance differences, and better support for unit/integration testing.
Rather than advocate specifically WCF, I'd recommend WCF Data Services or OData, with the stipulation that you'll need to secure it. If you go for pure WCF, you'll see that you'll end up creating a lot of code to handle retrieving the info from a database, and then sending that information right back out to your clients. It doesn't sound that bad, at first, but after about 30 entities in a database, you'll quickly grow tired of a pure WCF solution.
OData is great, it uses Entity Framework, and it quickly opens data manipulation for an existing database or one you are going to make. It will save you a ton of development time, if you can make your service secure. The format of the data response is flexible. There are plenty of client libraries ported for other programming languages as well.
The steps for securing a service are pretty simple. Always deploy to https. Any login or registration methods , need to be post methods, that return a token (Encrypted value), or a unique secret that can be encrypted and sent back for any subsequent requests. It's better to use the token, and have an expiration on the token.. because otherwise both your service and your app whether mobile or desktop, need to have a shared encryption / decryption method.
I am creating a new MVC4 project, and research has lead me to believe that communicating from javascript to the server side is better achieved now through web API framework rather than controller actions. Is my understanding correct on this?
I am presuming that I can share all my attributes etc between web API and MVC controllers so on the face it, it does not seem a massive change for me.
When I am setting up applications, I like to split components out in to projects. My plan was to have a MVC project and a web API project. But I have ran in to issues. For example I have ended up with 2 apps as such, separate routing set up etc etc.
So my question is, in a MVC application should the web API framework sit within the same project, or should the web API be separated into a project of its own and work around the issues?
Unfortunately you are wrong about that - I am presuming that I can share all my attributes etc between web api and mvc controllers so on the face it, it does not seem a massive change for me.
Many of the concepts used by Web API and MVC, even though similar at first glance, are actually not compatible. For example, Web API attributes are System.Web.Http.Filters.Filter and MVC attributes are System.Web.Mvc.Filter - and they are not interchangeable.
Same applies to many other concepts - model binding (completely different mechanisms), routes (Web API uses HTTPRoutes not Routes, even though they both operate on the same underlying RouteTable), dependency resolver (not compatible) and more - even though similar on the surface, are very different in practice. Moreover, Web API does not have a concept of areas.
Ultimately, if all you are trying to do achieve is to have a "new, trendy" way of serving up JSON content - think twice before going down that path. I certainly wouldn't recommend refactoring any existing code unless you are really looking into embracing HTTP and building your app in a RESTful way.
It all really depends on what you are building. If you are starting a new project, and all you need is to serve up some JSON to facilitate your web app - provided you willing to live with some potentially duplicate code (like the stuff I mentioned above), Web API could easily be hosted within the same project as ASP.NET MVC.
I would only separate Web API into a separate project if you are going to build a proper API for your online service - perhaps to be consumed by external customers, or by various devices - such as fueling your mobile apps.
IMO, security and deployment should drive your decision. E.g., if your MVC app uses Forms authentication but you're interested in using Basic authentication (with SSL) for your API, separate projects are going to make your life easier. If you want to host yout site at www.example.com but host your API as api.example.com (vs. www.example.com/api), separate projects will make your life easier. If you separate your projects and subdomain them accordingly and you intend to leverage your own API from your MVC app, you will have to figure out how to deal with the Same Origin Policy issue for client-side calls to your API. Common solutions to this are to leverage jsonp or CORS (preferably if you can).
Update (3/26/2013): Official CORS support is coming: http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API
After some degree of experience (creating API for apps and for mvc). I mostly do both.
I create a separate project for api calls that come from other clients or other devices (Android/IOS apps). One of the reasons is because the authentication is different, it is token based (to keep it stateless). I do not want to mix this within my MVC application.
For my javascript/jquery api calls to my mvc application, I like to keep things simple so I include a web api inside my MVC application. I do not intend to have token based authentication with my javascript api calls, because hey, it's in the same application. I can just use [authorize] attribute on a API endpoint, when a user is not logged in, he will not get the data.
Furthermore, when dealing with shopping carts and you want to store a users shopping cart in a session (while not logged in), you need to have this in your API as well if you add/delete products via your javascript code. This will make your API stateful for sure, but will also reduce the complexity in your MVC-API.
Steven from SimpleInjector (IoC framework) advises two separate projects: What is the difference between DependencyResolver.SetResolver and HttpConfiguration.DependencyResolver in WebAPI
I have recently done almost the same thing: I started with a new MVC 4 web application project choosing the Web API template in VS2012.
This will create a Web API hosted in the same application as MVC.
I wanted to move the ApiControllers into a separate class library project. This was fairly easy but the solution was a bit hidden.
In AssemblyInfo.cs of the MVC 4 project add similar line of code
[assembly: PreApplicationStartMethod(typeof(LibraryRegistrator), "Register")]
Now you need the class LibraryRegistrator (feel free to name it whatever)
public class LibraryRegistrator
{
public static void Register()
{
BuildManager.AddReferencedAssembly(Assembly.LoadFrom(HostingEnvironment.MapPath("~/bin/yourown.dll")));
}
}
In the MVC 4 project also add reference to the Api library.
Now you can add Api controllers to your own separate class library (yourown.dll).
Even if your project is so complex as to warrant two "front ends" then I would still only consider splitting out webapi into a separate project as a last resort. You will have deployment headaches and it would be difficult for a newbie to understand the structure of your solution. Not to mention routing issues.
I would aim to keep the system.web namespace isolated in the one "presentation layer". Despite the webapi not being presentational it is still part of the interface of your application. As long as you keep the logic in your domain and not your controllers you should not run into too many problems. Also, don't forget to make use of Areas.
In addition to setup the separate DLL for the Web.Api.
Just a Suggestion:
Create the Project
Nugget WebActivatorEx
Create a a class Method to be called upon app_start
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(API.AppWebActivator),"Start")]
[assembly:WebActivatorEx.ApplicationShutdownMethod(typeof(API.AppWebActivator), "Shutdown")]
Register a web.api routes inside the Start Method
public static void Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Reference the Project to the Web Project. to activate the Start Method.
Hope this helps.
I tried to split the API controllers into a new project. All I've done is to create a new library project, moved the controllers inside folder named API.
Then added the reference of the library project to the MVC project.
The webAPI configuration is left in the MVC project itself. It works fine.