How to identify the JSON response? - c#

I am developing the REST enabled WCF Service. I am using the following code inside the interface.
[OperationContract]
//[WebGet]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
List<String> GetProjects();
I want the method should return the JSON response. I am passing the parameter through the URL as follows.
http://localhost:51565/RestWebService/Search.svc/GetProjects
Now when I use the above URL in the address bar, the browser ask me for downloading the file. I am new the REST web service & also JSON. I am not aware whether in the above case I am getting the JSON response or something else ? How can I identify that the above response is the JSON response ?

Most of the the current browsers do not render Json when they see the media-type application/json. You will run into this problem with many media types. My suggestion is to just stop trying to debug using a web browser.
Install fiddler. It will save you.
Fiddler is a debugging tool for working with HTTP. You will be able to see exactly what is being transmitted to and from your service and you will be able to create POST requests in order to test your service.
It does take a bit of time to get used to but it is well worth it if you are doing any amount of work with HTTP.

Download file and look inside if you have a valid json object. Eventually parse using jQuery.parseJSON.
Browser propmts you to download because it received a content type is does not understand, does not have too much to do with content. It is not the responsability of the browser to decide if its a valid json but of the calling code.

I second fiddler for its JSON support, but for instances where you can call the service with a GET request then Chrome will display the result in the browser just fine.
Just copied this out a Chrome tab after calling a WCF service
{"GetDetailResult":{"Address":null,"MainPhotoURL":null,"Photos":[]}}

Related

Use postman or fiddler to check wcf service

http://example.com/ShaktiERPService/UpdateErpSrvc.svc?wsdl
i have one wcf service URL similar to above url... where i written one method (UpdateData) with 4 parameters. And this method is returning a string as response like "successfully updated" or "failed to update"
[ServiceContract]
public interface IUpdateErpSrvc
{
[OperationContract]
[WebGet(UriTemplate = "UpdateData/{Erp_Ord_No}/{SFDC_Order_No}/{usr}/{pass}")]
string UpdateData(string Erp_Ord_No, string SFDC_Order_No, string usr, string pass);
}
and My method is here:
public class UpdateErpSrvc : IUpdateErpSrvc
{
public string UpdateData(string Erp_Ord_No, string SFDC_Order_No, string usr, string pass)
{
ServiceRepository repo = new ServiceRepository();
return repo.UpdateData(Erp_Ord_No, SFDC_Order_No, usr, pass);
}
}
This service is working perfect in project...
But i want to check this in postman & fiddler....
I don't have any idea to check..
I tried so many time but didn't get response...
So please help me related to this problem..
Hope this helps you,
Fiddler is debugging tool.
Postman is best suitable to test your Web API methods. It can also be
used against 3rd party APIs and Open .
So, if your web service is with RESTful properties you can go with Postman to test the functionality of your web service.
However you can have fiddler in parallel to check the Request and Response in various formats such as
Normal Headers
without any extra effort.
Also, POSTMAN helps you to easily add the header fields , data, etc with Sophisticated User Interface when compared to Fiddler
Update 1:
As per your sample Code you are trying to using a GET request which works absolutely fine, how ever not a recommended standard.
Also, would like to know if your using Entity Framework for accessing the data, if so update your post with the necessary code to help you further.
You can use SOAPUI to test for WCF services. Check https://www.soapui.org/
to download. You can easily put your wsdl address and can just run your request.
Why don't you use WCFTestClient for checking your WCF service. It would clearly show you the request and response in XML format.

Return XML when consuming a secure web service

I am currently trying to consume a generated report as a webservice to integrate some data into our system. Because the service itself is generated, the response can change frequently as things are added to it. While the endpoint and response may change, the request body will always be the same (taken from soapui):
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<Execute_Report>
</Execute_Report>
</soapenv:Body>
</soapenv:Envelope>
I'm trying to figure out a way to make the above request for any endpoint (different reports) and allow for changes in the response. Ideally, I want to just return the raw XML of the response as I can allow for change easier with how I handle the XML if I'm not being tied to a data contract.
It is also worth noting that the service uses WS-Security and a Username/Password is passed as part of the request.
I've used WCF and the files generated from svcutil work great when I don't expect the service to change frequently. However because these webservices are generated change is expected, and if I can get away from it, I don't want to be at the mercy of re-generating a new file with svcutil whenever things change, or have to generate a file (and maintain) for all the different generated webservices.
At the end of the day the question is: How do I consume a webservice and return the raw XML while still being able to apply WS-Security to the request?
I kept searching around and found this answer:
.NET client authentication and SOAP credential headers for a CXF web service
This allowed me to do what I was after.

How to create a JSON variable from a SOAP Response?

I am using ASP.NET 4.0 and need to return a SOAP (XML) Response to a JSON variable within javascript on the page. Than I would like to be able to call the variable and it's properties as you would with any JSON variable. The Soap Web Service (.asmx) file is not on the server where I need to build the client-side (receiving the request and putting it into a JSON variable). Also, to make this more complicated, the XML Request that gets send to the Web Service needs to send a UserName and Password to be able to return the items.
The URL for the Web Service is here: http://ws.idssasp.com/members.asmx?wsdl
Figured I would create a Visual Studio Web Application Project (C#), which I was able to do and connect to the Web Service just fine, however, This needs to be on a page that javascript uses to output the items that come from the methods of the web service. So, a .aspx file would not work in this case, since it would need to output only the result of the web service response in a JSON variable within a tag (probably in the head of the page, but doesn't matter to me where). Or it could dynamically create a .JS file (which would probably be better, since it would be cached and wouldn't need to call the web service multiple times if the js file exists on my server). However, I'm not sure on what to build in Visual Studio to accomplish this? And I'm not sure on how it would be used to output it onto the page. I suppose the JSON variable could also be stored within a Members.json file on the server and could just call that to load up the json needed.
How to return a JSON array from SOAP, XML, Response... after sending a request to another server with UserName and Password in the header of the SOAP Request. There is a page here that explains the XML needed for the Request and what the response will look like: http://ws.idssasp.com/members.asmx?op=GetMemberList&pn=0
On this same page, they show you how to do it via PHP, but PHP is not available, and only have ASP.NET 4.0 available to me. Here is their PHP way of doing it:
$clientWS = new SoapClient('http://ws.idssasp.com/Members.asmx?wsdl');
$namespaceWS = 'http://ws.idssasp.com/Members.asmx';
$dmsClientU = '';
$dmsClientP = '';
$headerBodyWS = array('UserName' => $dmsClientU, 'Password' => $dmsClientP);
$headerWS = new SOAPHeader($namespaceWS, 'AuthorizeHeader', $headerBodyWS, false);
$clientWS->__setSoapHeaders(array($headerWS));
$results = $clientWS->GetMemberList();
print_r( $results );
How would I be able to do the same thing here is ASP.NET 4.0, but instead of returning the XML result, return a JSON variable that gets used within a script tag on the page?
Or maybe I am overthinking this and there is a better solution?
If you are connecting to the web service and retrieving objects without issues, you should be able to construct JSON objects out of the properties of the SOAP responses.
I suggest creating a web service in ASP.NET, converting the SOAP response to JSON in the C# server code, then using AJAX in the JavaScript of your page to retrieve the JSON from your web service. Basically, you would be creating your own specialized conversion web service for your project that sits in the middle.
Keep the credentials you need server-side for your .asmx conversion service. Whatever you do, do not put credentials in the client-side JavaScript for a web service call, even if it lets you avoid writing server-side code.
For some reference on ASP.NET web services:
http://msdn.microsoft.com/en-us/library/bb398998%28v=vs.100%29.ASPX
http://msdn.microsoft.com/en-us/library/bb763183%28v=vs.100%29.ASPX

Testing a REST Logging Web Service using C#

I've created a pretty basic REST Web Service in VS2012 using C#. The approach I've taken is seen below in one example:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "OpenSession/{key}/{source_userid}/{source_id}/{source_version}/{source_ip}")]
string OpenSession(string key, string source_userid, string source_id, string source_version, string source_ip);
The code works just fine and the service is up and running. I get responses, the tokens are handed out, etc. I figured wrapping the data in the URL was just fine as the service is built for logging, so in the end, calls would be (for example):
www.service.site/service.svc/2/5/12/HELLO
(BTW if there's a better way to do this while keeping it a REST service please let me know)
The problem I have is... how do I test this properly? I need to simulate 1,000 concurrent hits to this service and have built a custom C# Windows Application to do this, but I'm encountering a number of problems.
First, I have no idea how to use HttpWebRequest and the stream readers/writers to send/receive data properly in a manageable format. I see The requests have GET and PUT methods, etc. but I honestly can't seem to make heads or tails of separating the post data vs. the URL information. AFAIK I'm not really posting any data as all my data is embedded in the URL request itself; is this correct?
Also, I have no idea what "content type" to set the HttpWebRequest to in order to be compatible with my Operation Contract (I can see the enumeration of JSON but what's the "text" supposed to be?)
And on top of that, HttpWebRequest is monstrously slow. When I open a URL directly to the service (e.g. "http://localhost:51849/Scribe.svc"), it's fast, but the second I try to call a method (e.g. ""http://localhost:51849/Scribe.svc/GetStatus"), I get a 1.5-2 second delay (and I've done all the proxy fixes to ensure it's as fast as possible).
Any help would be greatly appreciated.
I don't know if you are aware of this utility:
SoapUI
You can use it to reference your service and generate the requests to test your service.
The installation is pretty straightforward. After installed, you have to click on file/new SoapUI Project.
Then, in the popup window, you fill in the "Initial WSDL/WADL:" field with your service's wsdl, like this:
http://localhost:51849/Scribe.svc?wsdl
It'll generate the client to correctly do the calls to your service.
Using soap ui you can even test doing a bunch of calls to stress up your service.
This is a good way to test your services.
AFAIK I'm not really posting any data as all my data is embedded in the URL request itself; is this correct?
Yes. That's how a GET request works. The data is passed on your url. You should only use GET requests when not changing the state of the data on the server, otherwise you should use post.
PUT methods you'll use when you want to create/update the data on the server.
I hope it helps.
Regards,
Rodrigo
Maybe you should consider using some performance tool.
There are plenty and them, should be easy to find one suitable for your pourpose.
Jmeter could be a good option.
This is a guide that show how to use Jmeter to test a REST Web Service.
Hope it can help.
Thanks for the responses! I actually have the testing system working now and can slam my service with thousands of timer-controlled sessions. The key to getting around the PUT request issue was to use empty settings:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "PUT";
req.ContentType = "application/json";
req.ContentLength = 0;
I did look at those tools, but for my specific needs, I found writing a custom timer-controlled app was the best approach.
I'm not sure if the delay is still problematic, or possibly even linked to the debug state. once I publish the service to Azure and test it remotely, I'll get a better idea if there's any latency issues with connectivity which are service based...

RESTful.NET service and preflight

I'm developing a RESTful web service with WCF and C#. The service works fine, but when I made a request from a static HTML page, using XMLHttpRequest, all browsers except IE (who else?) first send a prefligth message (https://developer.mozilla.org/en/http_access_control) requesting the available options for the service. This kind of messages only occur when I change the headers of the message in order to send a POST request.
My question/suggestion: do you know any way to give support to this kind of messages on WCF/.NET? My idea is to implement a method to handle the preflight message; the reply would be a standard reply message with all the available options (GET, PUT, POST, DELETE), because all this operations will be available, and also tells that the only type of data available for the data on the messages is JSON. After the reply the normal request would be sent by the browser, so everything should work right.
What do you think?
You can support OPTIONS in the same way you support POST with the WebInvoke attribute. Just change the method. There is nothing special about the OPTIONS request. You just need to set the Allow header in the response.
Problem solved! I've setted the Method attribute with * and now it works fine: first the preflight request is answered and then the real request is received and handled. Code follows:
[OperationContract]
[WebInvoke(UriTemplate="*", Method = "*")]
void HandleHttpOptionsRequest();
[OperationContract]
[WebInvoke(UriTemplate="*", Method = "*")]
void HandleHttpOptionsRequest();
This is a great solution and you can implement an IDispatchMessageInspector to add the necessary CORS headers quite easily.

Categories

Resources