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.
Related
We are starting a project which will consist in:
Web project (ASP.NET MVC)
IOS app
and both will consume data from a .NET WEB API service.
The WEB API service will expose a POST Method with the url "user/create". But i don't know how can i avoid another apps for making post to this url? I know i need a security protocol, but i wanted to know which one you recommend me, and if you have, an article where is it explained.
Thanks
web api 2 provides oauth authentication. You will need to get a token from the token end point of web api and pass that token in subsequent requests.
You should find lot of online resources if you search for web api 2 oauth.
We did something similar recently using OWIN OAuth 2.0 Authorization Server
Reference this ASP.NET page for details. Sample code is included as well for several different implementations.
For our purposes, we used the Client Credentials Grant section about half-way down the page. Our implementation involved server-server OAuth (Web API to MVC), but I bet it's pretty similar to have iOS connect. The only thing I would caution is to somehow encrypt the login credentials on the iOS side, and I'm sure there is a way to do that.
So you want the WebAPI to only be used by the MVC page? The best architectural method is to separate the two rather than leave both in one project. Why? Because the MVC app is a experience layer for humans. The WebAPI is an experience layer for the MVC app. Move it back where it can't be accessed.
You can add on tokens, etc, but the MVC app sits on the server, but is accessed on the client computer. The wider the scope of the application (ie, intranet or internet or something in between?), the more difficult the problem and the harder it is for your users to access the application. Moving the WebAPI internal and leaving the MVC app exposed guarantees external users cannot use the API.
The main reason WebAPI and MVC exist together in a single project (still a mistake in most instances, IMO) is you are exposing both to the same audience. If that is not your intent, don't do it.
I've got a stand alone WCF service providing REST services. As time goes on, I'm feeling like MS is going to reduce support for WCF and REST services, and I've already had to code in a bunch of hacks to get somethings working like CORS. Additionally, implementing https is another hack since it requires using OS functionality. (i.e. you have to install the certificate using an external application, which doesnt' make the service very self contained)
In anycase, I'm considering either a move to ASP.NET REST API and OWIN, or Java/Spring. I wanted to first see what it would take to move to ASP.NET REST, since I figured that should take the smallest amount of work, but I haven't found any good examples.
There's a pretty straightforward example on the asp.net site.
http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
setup a self-contained project i.e console app or windows service
initialise and setup you routes
create your Controller / API stubs
deploy
Regarding SSL, whether it's IIS or Apache you will have to configure it on the web server regardless.
I am new to APIs development and have to start building a REST API for the e-commerce website to be built and can be used by 3rd party: mobile app development company.
The eCommerce site is written in C#, ASP.net.
I have read about SOAP, REST, RESTFul on google.
My doubts are :
Where do I start? I have never created any API's before. Please mention the steps to start over.
The REST API is to be used with both Android and iOS mobile app. So, do we have to create a different client application for both?
Do we use some frameworks? If yes, then which frameworks to use?
As the website is written in dot net. Do we use Java or dotnet for REST API development?
What is the best way to create the REST API for mobile apps?
Please help me with my doubts.
Thanks in advance.
Here is Tutorial to build RESTFUL API in .NET.
My knowledge is in ASP.NET so I leave the Java guide for experts in that field.
RESTful API provided by Microsoft - which is called Web API - is a part of ASP.NET MVC, so you should start learning ASP.NET MVC, it's pretty easy for ASP.NET guys to learn ASP.NET MVC.
No, when you developed your Web Service, both iOS and Android would be able to communicate with your Web Service.
For Authentication, you gonna need libraries like Owin.
Since your main website is in .NET and not MVC, you should keep the Web Service files separate, for this, you can put Web Service file in a separate folder on the same host which the main website is, then create a sub domain to access the Web Service. By the way, you can create your Web Service using Java too, since it is separate from the main website, it makes no difference which technology you use.
The best way to create a REST API for a mobile app is if it is done by an expert! ;) There are many tools and frameworks out there that can be used to create RESTful Web Services, each one of them has some pros and cons, I prefer to use the one I know the best, which is Microsoft ASP.NET Web API, you should choose based on your current expertise.
P.S. If you gonna start learning ASP.NET MVC, I recommend to learn ASP.NET Core, which is the latest version of ASP.NET MVC, and is the future of this technology.
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.