I am new on android, i want to use asp.net webservices in my android app.
but i dont know how i can use this?.
i want to do with Restful method.But when i search in google, i found all tutorials in soap.
Is soap is compulsory for asp.net or there is ant other option available that we can use rest for asp.net in android.
i have follow this tutorials.link
You can always use JSON.
Json is the fastest data transfer mode across network, so your webservice should return data in Json format.
Once you have Json you can always render it and use it as needed.
Here is example to render data
http://www.tutorialspoint.com/android/android_json_parser.htm
You can create a WCF REST web service
http://msdn.microsoft.com/en-us/library/ms731082(v=vs.110).aspx
or an easier way is to create a new MVC4 web application, and update your Controller to extend Api Controller, then create a new web method that will return a HttpResponseMessasge like so:
public class MyController : ApiController
{
public HttpResponseMessage MyWebMethod()
{
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.Write([WRITE YOUR JSON HERE]);
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
Related
Thanks for your time , I have a simple question, in an asp.net MVC application, inside controllers is it possible that along with some methods returning View (ActionMethods) other could act as (or return) Json as a Web API (could be called from external apps).
Just trying to do a proper separations, hence trying to understand.
Thanks much.
You can make an action function like an API. Try something like the this.
// Controller/Action
[HttpGet]
public ActionResult IAmSpecial()
{
if (Request.IsAjaxRequest())
{
string[] objects = new string[] { "Foo", "Bar" };
return Json(objects);
}
return View();
}
This will return the IAmSpecial view if you browse to {domain}/{Controller}/IAmSpecial while it will return a JSON result if you use an AJAX Http Get request on the same url.
while it is possible to have controller methods which return Json data only, there are a number of considerations when you want to expose that data outside of the UI app.
Since you have an MVC app, I expect you have users and a way to login. Your controllers would more than likely be secured in some way, which works for the internal users of the application. Now you want to add one method which effectively becomes an API, available outside of the application and calls to it will have to be authenticated somehow.
What I would suggest is to split this up. You can create a separate project, which is a WebAPI one, in the same solution. The code which prepares the data can live in a class library you can then reference in both your MVC and WebAPI projects.
Your MVC app can call it and then return a view with that data, the WebAPI calls it and simply returns the data. You can now decide on a way of securing your API, maybe using Identity Server or some other way and you can keep adding things to it, without affecting the UI layer.
Your second option is to make the MVC app use the API when it needs to retrieve data, so both your public clients and UI use the same thing.
Whichever option you use, the idea is to not duplicate anything and at the same time provide the security layers you need.
I am beginner in software field. I have one ASP.Net MVC 5 (c#) project. In that I need to write one end point which can be called from a desktop app. Basically desktop app needs to send one integer value to my controller action aka end point. I know how to create a web api. So, I added a WebApi controller in my controller folder namely "HelloController" and below is the code.
public IHttpActionResult Follow(int y)
{
// some code
return Ok();
}
Question 1. Is that it? So, in my desktop app can I call now /HelloController/Follow/34
Question 2. Or Am I totally wrong. And I need some other end point and not the WebApi end point. Please guide me here.
P.S: My desktop app is in VB.Net
That is pretty much it. You'll want to enable Cors. This answer has some good information on setting Cors in ASP.NET MVC 5. There are two main ways to set CORS, the first way in the linked answer(setting the response header HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");) or in the web.config with:
Sorry, my mistake, Cors isn't required from desktop apps to api's. I'm used to setting Cors for web apps.
With the Web Api endpoint, you should be able to consume that from pretty much anything that can create a Web request. I don't specifically know VB.Net or I'd give you an example.
An example web request in C# would look something like this:
var url = someUrl;
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
var responseString = await response.Content.ReadAsStringAsync();
var deserializedData = JsonConvert.DeserializeObject<MyModel>(responseString);
}
Create an HttpClient, perform a Get request asynchronously. The response string is serialized JSON, so it must be deserialized to a usable model.
That's a basic example, but hope it helps.
Here is a website that contains VB.net examples for REST.
We have a server which has several types of api (custom XML API based on httplistener, SOAP API based on WCF and REST API based on WEB API). We want to move all API's to WEB API (there are many reasons) and it should be backward compatible.
One of the reason to support url structure: services/service1. services/service2. And in this case it should be on one port. It is intranet application which is distributed to multiple customers and it should be easy to deploy, install. So, we can not have a long configuration on customer side (proxing and otherts).
Are there easy way for implementation SOAP service on web api? At first look should be easy way to parse httprequest to typed soap envelope (based on existed contract) and serialize a answer. Of course, there many actions and data types in contract.
PS: I do not want to look into servicestack:)
Update:
The problem I described above can be fixed by proxing http request to soap service (It can work only with basichttpbinding without security. If WCF service require NTLM authentication it won't work):
[HttpPost]
public async Task<IHttpActionResult> SoapAction()
{
var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8111/soap")
{
Content = this.Request.Content
};
foreach (var header in this.Request.Headers)
{
httpRequestMessage.Headers.Add(header.Key, header.Value);
}
var responseMessage= await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
return ResponseMessage(responseMessage);
}
But I still want to know are there any SOAP parser in C# because my server supports NTLM authentication.
I wouldn't recommend to mix the technologies. Have one project for SOAP Apis and another one for the WebApi, sharing the same logic.
You have then one url for soap, the other one to webapi.
Edit:
I wouldn't do the SOAP Parser at all. That was the power of WCF and would keep on using it.
Since proxing is not an option (Which could be done in web.config and easily deployed), I would create a WebAPI endpoint which would redirect to SOAP API.
[HttpGet]
public IHttpActionResult Service1()
{
return Redirect("http://service.com/soap/services/service1");
}
Later, when migrating the logic, use the service itself.
[HttpGet]
public IHttpActionResult Service1()
{
var result = new ServiceLogin1().Execute();
if(result == null)
{
return StatusCode(HttpStatusCode.NoContent);
}
else
{
return Ok();
}
}
I think this is already answered here ASP.NET WebAPI + Soap
If what you are asking for is how to create REST wrappers that call into the SOAP implementations then library's like ServiceStack do this for you but if you want to do it yourself with WebApi it's pretty easy. Just make a separate project that has your SOAP service references in it wrapped in some sort of abstraction and then reference that in your WebApi project and call into it from your REST endpoints.
If what you are asking is how to host the SOAP interfaces in WebApi I think you are just making more work for yourself. Use the WCF scaffolding that MS has provided. WebApi for REST services, WCF for SOAP.
I'm having difficulty consuming a WCF REST service, which returns JSON, in a C# ASP.NET MVC application. I'm trying to consume the service in a Controller. I have a ASP.NET MVC project and a service project in the same solution. I've created an entry in my local IIS which points to the service project (i.e. http://localhost/SampleService/).The WCF Service works because I can access the URL and the correct JSON is returned.
Does anyone have any code samples on consuming the JSON via a Controller from a RESTful WCF Service?
You can use the DataContractJsonSerializer:
Here's an example:
var client = new WebClient();
var data = client.DownloadData("http://localhost/SampleService/GetJsonMessage");
var stream = new MemoryStream(data);
var obj = new DataContractJsonSerializer(typeof(string));
var result = obj.ReadObject(stream).ToString();
In your controller you can do this to view the result
return Content(result.ToString())
I used WebChannelFactory and it worked great.
You can either use the built-in DataContractJsonSerializer, or the JSON.NET library's JsonSerializer.
I prefer the latter, because it is more robust. Sometimes the DataContractJsonSerializer cannot deserialize a JSON object.
Sample code:
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonText);
To download the library, go to http://json.codeplex.com/
What is the best way to create a JSON web service? We have another team that is using Java and they insist to having all communication done using JSON. I would prefer to use WCF rather than any 3rd party framework.
I found this blog: http://www.west-wind.com/weblog/posts/164419.aspx, and it suggests that the Microsoft implementation is flawed with M$ specific crap.
If you use WCF and the 3.5 Framework, it couldn't be easier. When you mark your OperationContracts with the WebGet attribute, just set the ResponseFormat parameter to WebMessageFormat.Json. When the service is accessed RESTfully, it will return the data using the DataContractJsonSerializer.
It's really helpful to mark the POCOs that you want to JSON serialize as [DataContract] and to mark each serializable member as [DataMember]. Otherwise, you end up with funky JSON, as Rick pointed out in his blog post.
I maintain a mature Open Source alternative to WCF in ServiceStack, a modern, code-first, model-driven, WCF replacement web services framework encouraging code and remote best-practices for creating terse, DRY, high-perfomance, scalable REST web services.
It includes .NET's fastest JSON Serializer and has automatic support JSON, JSONP, CORS headers as well as form-urlencoded/multipart-formdata. The Online Demos are a good start to look at since they all use Ajax.
In addition, there's no XML config, or code-gen and your 'write-once' C# web service provides all JSON, XML, SOAP, JSV, CSV, HTML endpoints enabled out-of-the-box, automatically with hooks to plug in your own Content Types if needed.
It also includes generic sync/async service clients providing a fast, typed, client/server communication gateway end-to-end.
This is the complete example of all the code needed to create a simple web service, that is automatically without any config, registered and made available on all the web data formats on pre-defined and custom REST-ful routes:
public class Hello {
public string Name { get; set; }
}
public class HelloResponse {
public string Result { get; set; }
}
public class HelloService : IService<Hello> {
public object Execute(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
Above service can be called (without any build-steps/code-gen) in C# with the line below:
var client = new JsonServiceClient(baseUrl);
var response = client.Send<HelloResponse>(new Hello { Name = "World!" });
Console.WriteLine(response.Result); // => Hello, World
And in jQuery with:
$.getJSON('hello/World!', function(r){
alert(r.Result);
});
What is the best way to create a JSON web service? We have another
team that is using Java and they insist to having all communication
done using JSON. I would prefer to use WCF rather than any 3rd party
framework.
Here's an easy-to-follow walkthrough, which takes you through the process of setting up your first WCF Service, then linking it to a SQL Server database.
http://mikesknowledgebase.com/pages/Services/WebServices-Page1.htm
It uses Microsoft's beloved Northwind SQL Server database, and shows how to write a simple JSON WCF Web Service to read and write it's data.
Oh, and it then shows how to consume the JSON data using JavaScript or an iOS application.
Good luck !
I ended up using JayRock. Its fantastic piece of technology, just works. You don't get any NullReferenceExceptions like from this crap WCF if you don't configure it correctly.