WCF "Method Not Allowed" in Visual Studio integrated webserver - c#

I have two web projects in Visual Studio 2008 SP1, One hosting a WCF service and another that I am using to consume the WCF service. The service in question exposes a webHttpBinding endpoint and take JSON as input and returns JSON.
I have used Jquery ajax to consume the service from the client web app like so:
$(document).ready(function () {
var data = '{"myobject":{"Business":"PIZZA"}}';
$.ajax({
type: "POST",
contentType: "application/json",
data: data,
dataType: 'json',
url: "http://localhost:1212/JobInfo.svc/ReturnThisString",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
},
success: function(data) {
alert("BoolValue: " + data.GetDataUsingDataContractResult.BoolValue);
alert("StringValue: " + data.GetDataUsingDataContractResult.StringValue);
}
});
});
And I get the following error in the Firebug HTML request:
http://localhost:1212/JobInfo.svc/ReturnThisString 405 Method Not Allowed
But if run the exact same file in the web project that is hosting the project it works fine.
The hosting project is running on set port localhost:1212 and the client on localhost:RANDOM_PORT. As the localhost is the same I would imagine its not a Cross Domain issue? Or does the port part count also?
The server contract is as follows:
[OperationContract]
[WebInvoke(Method="POST",UriTemplate="ReturnThisString",
BodyStyle=WebMessageBodyStyle.Wrapped,
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json)]
EventListArgs ReturnThisString(EventListArgs myobject);
[Serializable]
[DataContract]
public class EventListArgs {
[DataMember( IsRequired = false)]
public string Business;
[DataMember( IsRequired = false)]
public string Feeder;
}
And the implemented code is:
public EventListArgs ReturnThisString(EventListArgs myobject)
{
return myobject;
}
This was added as a simple method to prove I had not just done something silly. What I like to call a sanity check. Its a simple function that takes a complex(of type other then string) JSON object as a parameter and returns a complex JSON object.
As you can see above I have two web project that use the Visual Studio Built in web server (local IIS install not possible). The above configuration does not work but if you can see I have also got the Darkside test page in the server host which is an exact copy from the client and this work with no problems at all.

Try using IIS Express
It's got the same features as a full blown IIS and requires no install.
A simple command line is all you need to start it up. It should get rid of the Casini related errors you were getting.

Related

WebServices not working after upgrading from VS 2012 to VS 2013

Edit (7-17-2014) It's been four days since I posted this question and I am still stumped. Can anyone offer suggestions or places where I can start looking? Based on what I've learned so far, it seems possibly VS 2013 is looking in a different location than VS 2012...could that be it...I need to modify my web service path?
I created a web application in VS 2012, that uses web services. Everything works as it should. I just upgraded to VS 2013 and now my web services gives an error.
When I check the result object, in the resultText, I see the error:
No web service found at: /testserver/WebServices.asmx
Not sure how to approach this since it works in VS 2012. Can someone help?
Thank you.
WebServices.asmx file:
<%# WebService Language="C#" CodeBehind="~/App_Code/WebServices.cs"
Class="WebServices.Services" %>
WebServices.cs Signature:
namespace WebServices
{
[WebService(Namespace = "http://MyCompanyInhouseserver.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class Services : WebService
{
Code...
}
}
Ajax: (Added this in case it is a coding issue that got exposed in VS 2013. Code breaks in the complete: section.)
var pageUrl = "/testserver/WebServices.asmx";
$.ajax({
type: "POST",
url: pageUrl + "/ValidateLogin",
data: "{'username': '" + self.username() + "', 'password': '" + self.password() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (result) {
if (result.responseJSON.d != null && result.responseJSON.d.UserId > 0) {
$(window.location).attr('href', 'startproject.aspx');
} else {
self.loginError("Invalid username/password");
}
}
});
Check the web project's properties in visual studio and go to the Web section. Determine if you are using Local IIS which will require you to Create a Virtual Directory as well as have IIS installed. If you have IIS Express you will also need to create a virtual directory; but note that off of the localhost is a port number, you may need to adjust your url to that port number as well as local host for testing purposes after you build and run the project.

Access Webservice from another Application

I have an WebService in C# and I want to access this webservice from another application.
Ex. Have one webservice running in localhost and i also have a website running in localhost, and this two projects are in diferents places. The question is: How do I invoke this webservice from my website with ajax, both in localhost.
The Code that i have is this:
WebService
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public String HelloWorld()
{
return "Hello World";
}
}
and Client
$.ajax({
type: "POST",
url: "localhost:52137/Service1.asmx?op=HelloWorld",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '',
success: function (data, status) {
alert(data.d);
},
error: function(data, status){
alert(status);
}
});
Try changing url to this:
url: "http: //localhost:52137/Service1.asmx/HelloWorld"
And BTW.. if the website is running on a different port than the service.. you still have xdomain issues.
CORS ASMX
As these two projects are in different places, it would be CORS request.
You need to enabled cross domain request in your service application as suggested in this article.
You can use $.getJSON which allow cross domain request.
As you're using C# you can create HTTP Handler as shown in this article.

JSONP no get value result

I'm doing a project for college where one WebSite sends commands to a Windows Forms application. This application is responsible for access to serial port and send and receive commands.
Communication between the Website and the Windows Forms application, I used Web Api, however after publishing, auditioning remembered that the localhost in a C # WebSite. Net's own site and not my Windows Forms application.
I changed the call to the Web Api directly use Ajax and not a controller.
In the examples I found I saw that I use JSONP, but I can not read the results and use it on my website.
The calling code and return seen by Chrome are below
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
jsonpCallback: "cmdTorre",
jsonp: "cmdTorre"
});
}
function cmdTorre(data) {
alert(data);
}
Response Header
Content-Length:10
Content-Type:application/json; charset=utf-8
Date:Tue, 10 Jun 2014 11:18:30 GMT
Server:Microsoft-HTTPAPI/2.0
Response
No Properties
Windows Forms APIController
namespace TCCWindows.Lib
{
public class GPSController : ApiController
{
[HttpGet]
public string Posicao()
{
var coordenada = TCCWindows.FormPrincipal.PegarCoordenadas();
return coordenada.Latitude + "|" + coordenada.Longitude + "|" + coordenada.Altitude;
}
}
}
First, you ajax call looks overly complicated try replacing it with :
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
success: cmdTorre,
error: function(err){
alert("You have a error"+err);
}
});
}
function cmdTorre(data) {
alert(data);
}
Please validate the new code carefully. I just typed it in here so can have errors. If this runs at this point you should probably see the error message. That is because your GPSController doesnt seem to be returning a valid JSONP (or JSON for that matter). Please read up on JSONP for more clarification but, I think if you modify your return statement to make it look like following, it should work. Assuming your controller is actually getting called and your network stuff is working:
return "cmdTorre({\"lat\":"+coordenada.Latitude+" , \"lon\":"+coordenada.Longitude+" });"
Basically your return string should look like following when printed on console:
function cmdTorre({
"lat": 23.34,
"lon":34.23,
"alt":50
});
Again I suggest you check the code I wrote for syntax issues as i just typed it up in here, but it should give you the idea.
So problems were:
The return string you are generating is NOT in JSON format
It is also not wrapped in a function call making it a invalid JSONP too.
Lastly my solution should get your code working and JSONP started but its not the right way to do things. Its more of a ugly hack. Your GPS controller should read the HTTP request for parameter called 'callback' which is a accepted convention for JSONP calls. Then instead of hardcoding the function name in the return statement, you should use the value of this callback parameter. Then you dont need to use a specific function like 'cmdTorre' in your jQuery. Instead a anonymus function like success:function(response){...} will work just fine.
Hope that helps.

How to debug Web Service? [duplicate]

This question already has answers here:
How to debug a web service in a C#/.NET solution from a web application
(5 answers)
Closed 8 years ago.
I am using visual studio and I have asp.net application as one project and a web service as another project.I am using web service in my asp.net application. There is some sort of problem im my webservice code.But i am unable to debug continuosly from asp.net application to web service.I put break point both in application and web service but break point not activated in web service and it shows me connection error.How can i do this while hosting on localhost?
If you're running web application as startup project, try running web service in another debug instance.
You can do it by right-clicking on web service project, Debug -> Start new instance
You should attach the debugger to w3wp (IIS process).
Here is a link that could help you.
If you want to debug in local system, You can set multiple start up projects.
You can set multiple startup by Solution properties.
Hope this help
Try to debug the service itself and see if it hits breakpoint. Just set the project that has service in it to be the main project and set the service to be the main start page.
If it doesn't hit the breakpoint it probably didn't load all the symbols. That happens if the project is set to, lets say, Release configuration and not Debug.
Is the web service running on a remote computer , if so you need to setup remote debug for the web service.
Can You please check that you add Service reference your web service or not other you can't access your web service function. I am useing web service in my project like this it's below
this is my web service code
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class JsonData : System.Web.Services.WebService
{
[WebMethod(Description = "")]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public StateData[] GetStateByCountryID(int ID)
{
StateData objStateData = new StateData();
LMGDAL.db_LMGEntities dbData = new db_LMGEntities();
var data = (from con in dbData.tblStates
where con.State_CountryID == ID
select new StateData
{
StateID = con.StateID,
StateName = con.StateName
}).ToList();
return data.ToArray();
}
then i add Service reference to my asp.net web form
this code in my form
<script type="text/javascript">
$(function () {
$("#ddlCountry").change(function () {
var countryID = $("#ddlCountry").val();
$.ajax({
type: "POST",
url: "JsonData.asmx/GetStateByCountryID",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: '{ID:"' + countryID + '"}',
success: function (msg) {
var data = msg.d;
var stateData = "";
$.each(data, function (index, itemdata) {
stateData += "<option value='" + itemdata.StateID + "' > " + itemdata.StateName + " </option>";
});
$("#ddlState").empty();
$("#ddlState").append("<option value='0'>-Select State-</option>");
$("#ddlState").append(stateData);
},
error: function () {
alert('Faild To Retrieve States.');
}
});
});
I think this will help you

Migrating ASMX Service to WCF Service - AJAX Post

I have a asp.net asmx service and i would like to convert it to a wcf service.
I'm having problems calling the wcf service from jquery ajax POST request with parameters.
if i call the WCF service without parameters or pass the parameter in a json format it works OK.
When executing the below jquery post to the wcf service i get error 500.
Please note , i cannot change the way the jquery request is made.
Original ASMX Service:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void SendStatus(string param1, string param2)
{
..................
}
jQuery POST:
var d = { param1: 1, param2: 2 };
$.ajax({
type: "POST",
url: "/Service1.asmx/SendStatus",
data: d,
success: function () { }
});
NEW WCF Service:
[OperationContract]
[WebInvoke]
public void SendStatus(string param1, string param2)
{
}
jQuery POST:
var d = { param1: 1, param2: 2 };
$.ajax({
type: "POST",
url: "/Service2.svc/SendStatus",
data: d,
success: function () { }
});
-- EDIT --
I recall this issue drove me nuts once before, so I went back for another look. Sure enough ... Given the requirement that the Javscript remain as written, I maintain that this is literally impossible with the current release of WCF. Consider the following points:
1) You need to use webHttpBinding, because that's the only binding that supports REST style services (basicHttpBinding and WSHttpBinding both use SOAP wrappers). (ref. here: BasicHttpBinding vs WsHttpBinding vs WebHttpBinding)
2) The AJAX call as written in this question uses a content-type of "application/x-www-form-urlencoded" (you can confirm this using Fiddler).
3) You can also confirm that WCF throws an exception before the service method even gets invoked. The exception is as follows:
The body style 'Bare' is not supported by 'WebScriptEnablingBehavior'. Change the body style to be 'WrappedRequest'.
But "bare" body style is Microsoft-speak for a REST request using basic parameters (ie, not "wrapped" in JSON or XML). That is, there is no possible configuration that would allow WCF to handle this specific AJAX request. You can even implement your own WebContentTypeMapper, and it still won't work. This guy is on to them: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2473190-consider-making-the-system-servicemodel-channels-r
My conclusion is that (given you can't use MVC, which would make this a piece of cake), you need to somehow route this request to a basic .ASPX page, and use the trusty old Webforms methods (Page.IsPostBack, Request.Params["param1"], etc).
-- END EDIT --
Per the other thread above, looks like there are a few parameters you need to add/fix in your AJAX call:
...
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(d)
...
If you can't change the client-side code, you should not migrate these endpoints from ASMX to WCF. WCF uses a different, less-flexible serializer than ASMX and it's likely that you'll run into trouble that can only be resolved by changing how data is sent, received, and/or handled on the client-side.
If you're willing to deal with that turmoil anyway, a much better migration path would be waiting until ASP.NET Web API is shipped and moving to it. If you move to WCF now, you'll just be behind again later this year when Web API is released.
I think you have to pass string parameter values in double quotes (""). Like this:
var d = { param1: "1", param2: "2" };
$.ajax({
type: "POST",
url: "/Service2.svc/SendStatus",
data: d,
success: function () { }
});
Hope this will work.
500 error code means parameter values didn't match with required values.

Categories