I am hoping someone can point me in the right direction here. I am trying to create web service that will return ajaxified results. Specifically, I want to write a web service that will fetch email through a secure connection. However, rather then have the web service return every single email, I just want to fetch maybe 5 emails at a time. I've always used Ajax as a client helper technology and not sure how to go about implementing this on a server side, or if its even possible. Can someone please point me to some ideas or some suggestions on how I can accomplish this?
I am using ASP.NET/C#, by the way.
There are a number of ways to return "ajaxified" results (JSON) from a web/wcf services.
A WebServices have the attribute [ScriptMethod(ResponseFormat = ResponseFormat.Json)] you can use (and find some examples), WCF services may be configured to return JSON (here is a nice post: http://www.west-wind.com/Weblog/posts/164419.aspx)
But actually I prefer to use ASP.NET MVC to do this. Basically all you need to do in this case is to say return Json(myObject); inside your controller's method.
Here is an example: http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=399
And here is the StackOverflow question about it: ASP.NET MVC controller actions that return JSON or partial html
The returned JSON is standard and can be consumed on the client using any library (jQuery, etc) and in your controller you do all you want and return what you want.
Related
For some days now i have been struggling on a project where i need to provide a URL to enable me to receive a JSON response(precisely this my first time of calling a web API)
This is the scenario:
- First the company has a web service that i need to consume and send a bill prompt to our client and so far it has been successful
- Second , they ask me to implement a callback and give them the URL where they will call me to send the status of the bill whether our client has confirm the bill prompt or not(this is where i am stacked)
When i get the JSON data i can easily use it to do what i want but my problem is how to implement the web page that the company will call to send the status.
Please a sample code will help me a lot.Thanks
What you are trying to achieve is called WebAPI. You expose HTTP endpoints using Controllers to the Internet and consumers of your API may utilize them to POST the status back.
You are describing creating an API. Basically, you create an endpoint url using a controller in C#. It's within this controller that you receive data from "the company" and process it, and do whatever you need to do after that. If you use the standard MVC framework build into C#, it's fairly straight-forward. Here is an example of a callback url we are using in a three-legged OAuth procedure. The last step involves a third party sending a request to our callback url and posting some data. We are using a model as a parameter. But you can use simple structures (int, string, etc) as well. As log as the names of your params match the names that the third party sends in their query string or POST, the MVC framework will handle the variable assignment automatically. The serialization/deserialization is built in to the framework.
Here is a small example of how we have implemented a callback url in one of our apps:
public class MyAuthenticatedController : Controller
{
public ActionResult Index([FromUri]MyAuthenticatedModel model)
{
logTheResponse(model);
if (model == null)
{
throw new HttpException(401, "Auth Failed");
}
}
}
The third party would hit the url:
http://app.mydomain.com/myauthenticated
Using the GET method.
If you don't want to build an ASP.NET Web API Project, you can do this easily with an Azure Function.
See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-generic-webhook-triggered-function
I'm working on my first Asp.Net Core project, which is to support both a web client, and a Game client (written in Unity).
Now, I started with the default Asp.Net Core Web Application project template provided by Visual Studio 2015, including authentication for Individual User Accounts.
Most, if not all of the generated controllers are returning views, following this pattern in general:
[HttpGet]
[AllowAnonymous]
public IActionResult Get()
{
//Do something smart
return View();
}
This method returns a View as you can see and all is good when requested by the web client.
But what if the Game is sending a request to the same method?
In that case a JSON response is expected (not a View/html document), and my question is what is the recommended "pattern" for supporting this in Asp.Net Core?
Should I place the api returning JSON in separate controllers, hence duplicating some logic? It doesn't feel right to me...
Or should I check the request for an expected response format, and implement logic for returning different responses based on this?
I don't particularly like that approach either...
To me, it seems Asp.Net Core messes things up by providing UI formatted responses directly from the API, but it might be something I've missed here...
Any pointers?
You could move the logic into a class to be called by the controller if you want separate controllers or actions for the Webpage and game.
This would be better and follow the single responsibility rule rather than one action returning two response types
When the return type is IActionResult you can also return Json messages for example as return Json(myReturnObject). You can add an if to return a JSON message and when it is false it will return the view.
You can add an if based on X-Requested-With:
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
return Json(myObject);
}
What I would recommend is to split the requests in different controller methods by response type and add the shared code/logic in a private method or to another class, probably you will use this elsewhere too. By doing this you will be able to do proper tests and won't get confused when it will return the view or a json message.
Hope this helps.
I am currently following this tutorial to create a simple REST service using Web Api. Note this is my first time doing something like this and I am just trying to learn more.
http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations
I have followed all the instructions and have it successfully running on my localhost. I understand that in this tutorial the URI for all my GET requests look something like:
localhostapi/products/id
And I understand that, and how to perform simple GET requests in the URI and see it actually occuring using my developer tools in my browser.
Now my question is... How do I make POST/DELETE/PUT requests and actually see what they are doing? The guide wasn't too clear, do I pass in parameters into the URI? Does the URI change when I want anything but a GET request? This text here seems to explain it but I do not understand:
The method takes a parameter of type Product. In Web API, parameters with complex types are deserialized from the request body. Therefore, we expect the client to send a serialized representation of a product object, in either XML or JSON format.
It's quite easy to make POST, PUT, DELETE requests. You just need to install Fiddler at http://www.telerik.com/download/fiddler
Next, install and run it. Go to the Composer tab on the right hand side. Next, put your local host URL, and the request method, and other data like the screenshot below
You can write unit tests, like
[TestMethod]
public void GetAllProducts_ShouldReturnAllProducts()
{
var testProducts = GetTestProducts();
var controller = new SimpleProductController(testProducts);
var result = controller.GetAllProducts() as List<Product>;
Assert.AreEqual(testProducts.Count, result.Count);
}
This link also This one may help.
more:
How to call ASP .NET MVC WebAPI 2 method properly
Sending C# object to webapi controller
You can set a breakpoint on your controller methods that handle the post/delete/put.
Same thing in your browser at the point where you call the post/delete/put (presumably in a jquery request)
You can also unit test your controller methods:
http://www.asp.net/mvc/tutorials/older-versions/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs
In our application, which is Single Page application, we are using MVC controller(Action methods as API) for CRUD operation's. Which I feel its wrong.
Can someone tell me if its correct?
Eg:-
I have an API Controller say :-
public class MockAPIController : ApiController
{
// GET api/MockAPI/5
public ClassA GetSomething(int id)
{
return new ClassA();
}
}
and this can be called from client-side using /api/MockAPI/GetSomething/1. Similarly if I create MVC Controller like:-
public class MockAPIController : Controller
{
// GET api/MockAPI/5
public ActionResult GetSomething(int id)
{
return new JsonResult(new ClassA(),JsonRequestBehavior.AllowGet);
}
}
Still, I can get it work. Can some-one tell me whats demerit of using MVC controller for API?
EDIT:-
Is it recommended to use MVC Controller for API methods?? If Not, then can someone point out the -ve aspect of it?
Using the web API you can return objects as normal and your clients can specify the content-type.
This will automatically serialize the objects to xml or json without the need to specify a new action just to change the return type.
So your API call will always remain as:
public ClassA GetSomething(int id)
{
return new ClassA();
}
But it is capable of returning xml and json without any changes in the controller.
Web API provides cleaner way to craft your HTTP responses. It is extremely extensible, testable and faithful to the HTTP spec.
Web API was NEVER intended to provide an "out-of-the-box" REST framework.
MVC is a HTTP framework, optimized for serving content to a Web Browser. Web API has no bias as to what client is using it.
As per my understanding,
MVC controllers are extended over API Controller. You can do almost
everything what can be done with API Controller.
(People please correct me if I am wrong, its purely my understanding which I am sharing!)
Now, if your application is a web based application/internet or intranet where you have very few api call's then you can stick with MVC Controllers. Only care that need to be taken care is sending data as JsonResult(basically serializing`to JSON or whatever). If you have more funda of SPA, the API controllers is what you need.
I myself have not found much articles stating a strong line separating what to use when, it's always a developers pain to decide and implement.
It's less about merit and demerit of using ApiControllers in place of Controllers, and more about implementation and usage.
ApiControllers are specifically meant for building REST-ful Apis which return serialized data to the client in simplest form.
And, using controllers you can return Views, Different Types of ActionResults in different form. You can definitely convert the type of data you are returning, like the way you are using here but it's not the same with ApiControllers.
I was thinking ,
The WebApi along with routing mechanism works in such way that it reads the http verb ( GET POST etc...) and then searches for matched method names / parameters :
For example :
If it's GET and the URI is api/Customers/5:
method should start with Get
if it has ID so search a method which accepts int as parameter.
etc. (there are more rules).
I mostly believe they did it using reflection.
Question :
Isn't it a performance hit , for every URI request - to search all this data just to attach a method ?
Where I could easily send a very short string from a client which will imply on the method on the server side ?
Why not doing it the simple way ? Ok cause we want to use http verbs as meaning. OK. but so much operations just to execute a method
example #1
get api/Customers/5
could be
a.ashx?m=gc&id=5 (method=GetCustomer & id=5)
example #2
put api/Customers/5?v=123
could be
a.ashx?m=uc&id=5?v=123' (method=UpdateCustomer & id=5 & value=123)
mine is even shorter.
Dont get me wrong. I believe this api was done by very smart people who knew what they talk about.
Just want o know what am I missing.
Web api has a lot of options that you don't have with HTTP Handler if you don't code it
Full list: http://www.asp.net/whitepapers/mvc4-release-notes#_Toc317096197
OData support (via Queryable attribute)
Content Negotiation
Filters
Model binding and validation
Ability to self host outside of IIS
Link generation to related resources that incorporates routing rules
Full support for routes/routing
Ability to create custom help and test pages using IApiExplorer
Performance comparison HttpHandler vs WebAPI: http://www.west-wind.com/weblog/posts/2012/Sep/04/ASPNET-Frameworks-and-Raw-Throughput-Performance
As always, you need to choose the the technology that suits you best, if you want performance go with Http Handler. If you want flexibility and rest go with Web API. You might want rest if you expose web services that other will consume