Web service error when invoked from web form - c#

I have a program that utilize a web service. When this web service is tested on its own (run on ie AS .asmx) runs fine but when tried to be called from inside the web form it produces the following error:
Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The web servce is:
public Check1 () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void check2(string destination)
{
Server.Transfer(destination);
}
}
And the web form from which is called is:
protected void Button1_Click1(object sender, EventArgs e)
{
localhost.Check1 new2 = new localhost.Check1();
new2.check2("Ipal_apoth_page.aspx");
}

A web service is intended to be a data interface, not a web page server, which is why XML is expected. Web service protocols use XML format for their communications, e.g. WSDL or SOAP. The .aspx page you attempt to transfer the processing to will return HTML.
It may be that when you tried it in a browser, the browser was permissive enough to interpret the repsonse from the web service in the way you wanted even though that is not how it is meant to be used.
A better thing to practise with would be something simple like adding two numbers.

Related

NSwag - Incorrect Auto Generated "BaseURL"(Host) In Swagger Services

I have a C# WebForms application where I'm using swagger initialized in my Global.asax in the following way:
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapOwinPath("swagger", app =>
{
app.UseSwaggerUi3(typeof(Global).Assembly, settings =>
{
settings.MiddlewareBasePath = "/swagger";
settings.DocumentTitle = "API";
settings.GeneratorSettings.DefaultUrlTemplate = "api/{controller}/{action}/{id}";
settings.GeneratorSettings.Title = "API";
settings.GeneratorSettings.Description = "REST interface for API";
settings.GeneratorSettings.UseControllerSummaryAsTagDescription = true;
});
});
}
I often deploy to a app pool and website that supports may different URL's for the various instances I'll have:
https://testci1.ABC.com
https://testci2.ABC.com
etc..
I've noticed that when I navigate to the swagger URL on one of my websites that often times the URL it wrong, for instance, when I navigate to "https://testci2.ABC.com/swagger" I see a "BaseURL" of:
[ Base URL: testci1.ABC.com ]
Which is wrong, and causes all my swagger services call to fail due to IIS security around cross URL requests.
There is a great deal of discussion on this topic, but very little specific to C#. How to I get NSwag to generate a base URL("host" technically) from I've navigated to, it seems to be caching and/or incorrectly generating and storing the wrong baseURL?

How to access a WCF Service within my webpage in vs2010?

I have created a simple Web Service application and used SvcUtil.exe to generate the two needed files named MyService.cs and app.config.
What I want to do now is be able to use this webservice from a web-app or webpage.
What I was doing until now was creating my website and creating an angular factory that would use ajax to call the various functions on a class that I used to create for the purpose of dealing with those requests only. For example I would have the following function inside a file name fhandler.aspx.cs:
namespace MyApp
{
[ScriptService]
public partial class fHandler: System.Web.UI.Page
{
// Save Interests Stress Test in List.
[WebMethod]
public static string saveDataJS(string data)
{
...
This would get called by an ajax request that would return a promise like this:
saveData: function(data) {
var senddata = {
'data': data
};
return $http({
method: 'POST',
url: 'http://' + location.host + '/fHandler.aspx/saveDataJS',
data: senddata,
headers: {
"Content-Type": "application/download; charset=utf-8"
}
});
},
Now that I am using web-services though I am not sure how to approach this.
What would be the best set-up for consuming a WCF service from a webpage?
Assuming we skip the create another project inside your solution, add MyService.cs and app.config to it and add a Reference to your service, part.
This tutorial once helped me a great deal with creating and consuming a WCF service.
To consume a WCF service, you simply have to add a service reference to your project. Have a look at the tutorial, it is all described with pictures.
Solution Explorer > {your project} > Add Service Reference.
After that, you can enter the URL of your service. Afterwards, you should be able to see all public methods your service offers:

Run method only once when IIS starts ASMX service, then store results globally

Firstly I must apologise if my terminology is off. This is the first time I've explored .asmx so I've probably gotten some things wrong. I'm mentioning this because I want you to correct me as it is an invaluable learning experience and I need to get it right.
I'm writing an Ajax enabled .asmx web service to allow two browser based systems to talk to each other. In order for this to work I must initially authenticate with one of the systems to get the URL to use for all subsequent API calls to that same system. I only want to do this one time when the service is started and then remember this across all calls to all webmethods.
How do I run a method only one time when the service is loaded
by IIS?
How do I store the result globally so that it can be
accessed by every call to my webmethods?
I've seen two posts that touch on this ( 1 | 2 ) but neither made enough sense to help me.
I think I need to add a Global.asax file and store the details in there, but I'm not sure if this is right and I still don't know how to run the method only once. Can I just override Application_Start in here? This is what I would do on an ASPX page but I don't know how similar these two technologies are.
I've seen recommendations to use the constructor to run the method but it's my understanding that this may be called more than once so would be incorrect for my scenario.
For clarity my project currently only has two files, handler.asmx and handler.cs.
Handler.asmx
<%# WebService Language="C#" CodeBehind="~/App_Code/handler.cs" Class="Handler" %>
Handler.cs
[WebService(Namespace = "http://localhost/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class Handler : WebService {
public Handler () {
// empty
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetSomeInformation() {
// does some stuff and then returns a string
}
}
This is what the Global.asax looked like after I added it:
Global.asax
<%# Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
}
void Application_End(object sender, EventArgs e)
{
}
// and all the other methods here like error, session start/end etc

AjaxMethods in Windows Azure not working

We are showing reports in our Azure web application using ReportViewer (rdlc) control in VS2010 which is working perfectly. Recently my client asked me to capture the the Print event for ReportViewer and log an entry on the server. I've hooked the with the print button.. This works perfectly when I run the web application on a local environment. However, on Azure, the Ajax method never gets called from client side. Please suggest what to do? Is there a limitation for Ajax in Azure Environment?
I'm registering the Page on Page_Load in code behind
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(Pages.Report));
ImageButton btnPrint = new ImageButton();
btnPrint = ((ImageButton)(this.FindControl("ctl00$" + ReportViewer1.ClientID.Replace("_","$") + "$ctl06$ctl06$ctl00$ctl00$ctl00")));
btnPrint.Attributes["onclick"] += "attachEventForPrint();";
}
[AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)]
public static void LogEvent(int pLoggingEvent)
{
// Addded logic to log event
}
And in ASPX file following function was added in JS
function attachEventForPrint() {
if (typeof (Report) != "undefined") {
Report.LogEvent(4);
}
}
The good news is that I don't think there's any limitation with using ajax controls - I've used a few and they just worked.
Some things to check might be:
can you use Fiddler to view the HTTP trace - is a request being sent to the server when you click on the the print button?
can you use a javascript debugger to check that there are no errors being reported when attachEventForPrint occurs?
are there any issues here with "State" - especially with Session storage?
One other thing to check is whether there is a more maintainable way to access the print button - the "$ctl06$ctl06$ctl00$ctl00$ctl00" just looks like it is asking for trouble either now or at some point in the future

Calling a Java Web service from silverlight throws an exception

After my previous question HERE, I found the solution (well, part of it).
Here's the code for Java part:
#WebService
public class MyWebService
{
#WebMethod
public String myMethod()
{
return "Hello World";
}
#WebMethod
public int Add(#WebParam(name="a") int a,
#WebParam(name="b") int b)
{
return a + b;
}
public static void main(String[] args)
{
String address = "http://127.0.0.1:8023/_WebServiceDemo";
Endpoint.publish(address, new MyWebService());
System.out.println("Listening: " + address);
}
}
And Here is the Silverlight part:
private void SearchResultList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MyWebServiceClient proxy = new MyWebServiceClient();
proxy.AddCompleted += proxy_AddCompleted;
proxy.AddAsync(2, 3);
}
void proxy_AddCompleted(object sender, AddCompletedEventArgs e)
{
txtSearch.Text = e.Result.ToString();
}
But when I run this, e.Result throws an exception.
What am I missing/ How should I solve it?
Note that this code runs perfectly in C# Console application (when it's not async). But when I run the async code, it doesn't work.
Thanks in advance.
I guess you are getting a System.ServiceModel.CommunicationException when trying to access the Java Webservice from Silverlight.
There is nothing basically wrong with your code, and it should also work with async calls in C# Console App.
The main problem is that Silverlight (as a browser plugin) enforces some security restrictions that prevent a Silverlight Application to talk to another server than the one loaded from (defined by server name and port) without further configuration. This behaviour can be configured as described here (also search for "silverlight cross-domain calls" or "silverlight cross domain policy").
This restrictions (normally) do not apply to desktop or console applications so they'll work fine with the same web service.
To make your code work you need to host the Silverlight Application inside the same "project" / website than your webservice (so I suppose, the self-hosting webservice won't work and you need to switch to Java web project where the webservice is to be hosted). As the Silverlight Application basically consists of an enclosing HTML file plus the referenced binaries, you can host it on any server, e.g. Apache Tomcat.
Hope this helps.

Categories

Resources