Search Results

Search found 61 results on 3 pages for 'webinvoke'.

Page 1/3 | 1 2 3  | Next Page >

  • Not able to access any mothod with the attribute [webinvoke ] in WCF Restful services

    - by user1335978
    I am not able to access any method with the attribute [webinvoke] in a RESTful WCF service. My code is like this: [OperationContract] [WebInvoke(Method = "Post", UriTemplate = "Comosite/{composite}", ResponseFormat = WebMessageFormat.Xml)] CompositeType GetDataUsingDataContract(string composite); On executing the above service I am getting an error message Method not allowed. I tried many ways, by modifying the urltemplate, method name and method type etc. but nothing is working out. But if I use the [WebGet] attribute the the service method is working fine. Can anybody suggest me what can I do make it work? Thanks in advance... :)

    Read the article

  • Philosophy of [WebInvoke(ResponseFormat = WebMessageFormat.Json)]

    - by Mikey Cee
    Hi everyone, I'm writing what I'm referring to as a POJ (Plain Old JSON) WCF web service - one that takes and emits standard JSON with none of the crap that ASP.NET Ajax likes to add to it. It seems that there are three steps to accomplish this: Change to in the endpoint's tag Decorate the method with [WebInvoke(ResponseFormat = WebMessageFormat.Json)] Add an incantation of [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] to the service contract This is all working OK for me - I can pass in and am being returned nice plain JSON. If I remove the WebInvoke attribute, then I get XML returned instead, so it is certainly doing what it is supposed to do. But it strikes me as odd that the option to specify JSON output appears here and not in the configuration file. Say I wanted to expose my method as an XML endpoint too - how would I do this? Currently the only way I can see would be to have a second method that does exactly the same thing but does not have WebMethodFormat.Json specified. Then rinse and repeat for every method in my service? Yuck. Specifying that the output should be serialized to JSON in the attribute seems to be completely contrary to the philosophy of WCF, where the service is implemented is a transport and encoding agnostic manner, leaving the nasty details of how the data will be moved around to the configuration file. Is there a better way of doing what I want to do? Or are we stuck with this awkward attribute? Or do I not understanding WCF deeply enough?

    Read the article

  • Webinvoke to POST JSON with ajax call

    - by G-Man
    This is my first time that I an using WCF Service with Knockout. I want to POST an entire view model as a JSON object with an ajax call. This is the error message that I get: Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior' I have noticed that some developers send each value as a parameter which I feel is unnecessary especially if you work with a big object. This is my WCF method: [OperationContract] [WebInvoke(UriTemplate = "AddNewEvent?newEvent", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] public bool AddNewEvent(Models.DAL_CRMEvents newEvent) { Entities.CRMEntities dbCRM = new Entities.CRMEntities(); //Models.CRMEvents crmEvent = new Models.CRMEvents(); Entities.Event crmEvent = new Entities.Event(); crmEvent.EventDateCreated = Convert.ToDateTime(newEvent.DateCreated); crmEvent.EventActive = true; crmEvent.EventDescription = newEvent.Description; crmEvent.EventDate = Convert.ToDateTime(newEvent.Date); crmEvent.EventTimeStart = TimeSpan.Parse(newEvent.TimeStart); crmEvent.EventTimeEnd = TimeSpan.Parse(newEvent.TimeEnd); crmEvent.EventAllDay = newEvent.AllDay; dbCRM.AddToEvent(crmEvent); return true; } This is my ajax function function SaveEvent (data) { var s = { newEvent: ko.mapping.toJS(data) } alert(data.AllDay()); $.ajax({ type: "POST", url: "../Services/CRMDataService.svc/AddNewEvent", data: JSON.stringify(s), contentType: "application/json; charset=utf-8", dataType: "JSON", success: function (result) { alert(result); }, error: function (jqXHR, textStatus, errorThrown) { if (textStatus == "error" && errorThrown != "") { var n = noty({ text: errorThrown, type: 'warning', dismissQueue: false, modal: true, layout: 'center', theme: 'defaults', callback: { } }) } } }) }

    Read the article

  • Unable to call RESTful web services methods

    - by Alessandro
    Hello, I'm trying to dive into the RESTful web services world and have started with the following template: [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class Test { // TODO: Implement the collection resource that will contain the SampleItem instances [WebGet(UriTemplate = ""), OperationContract] public List<SampleItem> GetCollection() { // TODO: Replace the current implementation to return a collection of SampleItem instances return new List<SampleItem>() {new SampleItem() {Id = 1, StringValue = "Hello"}}; } [WebInvoke(UriTemplate = "", Method = "POST"), OperationContract] public SampleItem Create(SampleItem instance) { // TODO: Add the new instance of SampleItem to the collection throw new NotImplementedException(); } [WebGet(UriTemplate = "{id}"), OperationContract] public SampleItem Get(string id) { // TODO: Return the instance of SampleItem with the given id throw new NotImplementedException(); } [WebInvoke(UriTemplate = "{id}", Method = "PUT"), OperationContract] public SampleItem Update(string id, SampleItem instance) { return new SampleItem { Id = 99, StringValue = "Done" }; } [WebInvoke(UriTemplate = "{id}", Method = "DELETE"), OperationContract] public void Delete(string id) { // TODO: Remove the instance of SampleItem with the given id from the collection throw new NotImplementedException(); } } I am able to perform the GET operation but I am unable to perform PUT, POST or DELETE requests. Can anyone explain me how to perform these operations and how to create the correct URLs? Best regards Alessandro

    Read the article

  • Help deciphering exception details from WebRequestCreator when setting ContentType to "application/json"

    - by Stephen Patten
    Hello, This one is real simple, run this Silverlight4 example with the ContentType property commented out and you'll get back a response from from my service in xml. Now uncomment the property and run it and you'll get an exception similar to this one. System.Net.ProtocolViolationException occurred Message=A request with this method cannot have a request body. StackTrace: at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at com.patten.silverlight.ViewModels.WebRequestLiteViewModel.<MakeCall>b__0(IAsyncResult cb) InnerException: What I am trying to accomplish is just pulling down some JSON formatted data from my wcf endpoint. Can this really be this hard, or is it another classic example of just overlooking something simple. Edit: While perusing SO, I noticed similar posts, like this one Why am I getting ProtocolViolationException when trying to use HttpWebRequest? Thank you, Stephen try { Address = "http://stephenpattenconsulting.com/Services/GetFoodDescriptionsLookup(2100)"; // Get the URI Uri httpSite = new Uri(Address); // Create the request object using the Browsers networking stack // HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(httpSite); // Create the request using the operating system's networking stack HttpWebRequest wreq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(httpSite); // http://stackoverflow.com/questions/239725/c-webrequest-class-and-headers // These headers have been set, so use the property that has been exposed to change them // wreq.Headers[HttpRequestHeader.ContentType] = "application/json"; //wreq.ContentType = "application/json"; // Issue the async request. // http://timheuer.com/blog/archive/2010/04/23/silverlight-authorization-header-access.aspx wreq.BeginGetResponse((cb) => { HttpWebRequest rq = cb.AsyncState as HttpWebRequest; HttpWebResponse resp = rq.EndGetResponse(cb) as HttpWebResponse; StreamReader rdr = new StreamReader(resp.GetResponseStream()); string result = rdr.ReadToEnd(); Jounce.Framework.JounceHelper.ExecuteOnUI(() => { Result = result; }); rdr.Close(); }, wreq); } catch (WebException ex) { Jounce.Framework.JounceHelper.ExecuteOnUI(() => { Error = ex.Message; }); } catch (Exception ex) { Jounce.Framework.JounceHelper.ExecuteOnUI(() => { Error = ex.Message; }); } EDIT: This is how the WCF 4 end point is configured, primarily 'adapted' from this link http://geekswithblogs.net/michelotti/archive/2010/08/21/restful-wcf-services-with-no-svc-file-and-no-config.aspx [ServiceContract] public interface IRDA { [OperationContract] IList<FoodDescriptionLookup> GetFoodDescriptionsLookup(String id); [OperationContract] FOOD_DES GetFoodDescription(String id); [OperationContract] FOOD_DES InsertFoodDescription(FOOD_DES foodDescription); [OperationContract] FOOD_DES UpdateFoodDescription(String id, FOOD_DES foodDescription); [OperationContract] void DeleteFoodDescription(String id); } // RESTfull service [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class RDAService : IRDA { [WebGet(UriTemplate = "FoodDescription({id})")] public FOOD_DES GetFoodDescription(String id) { ... } [AspNetCacheProfile("GetFoodDescriptionsLookup")] [WebGet(UriTemplate = "GetFoodDescriptionsLookup({id})")] public IList<FoodDescriptionLookup> GetFoodDescriptionsLookup(String id) { return rda.GetFoodDescriptionsLookup(id); ; } [WebInvoke(UriTemplate = "FoodDescription", Method = "POST")] public FOOD_DES InsertFoodDescription(FOOD_DES foodDescription) { ... } [WebInvoke(UriTemplate = "FoodDescription({id})", Method = "PUT")] public FOOD_DES UpdateFoodDescription(String id, FOOD_DES foodDescription) { ... } [WebInvoke(UriTemplate = "FoodDescription({id})", Method = "DELETE")] public void DeleteFoodDescription(String id) { ... } } And the portion of my web.config that pertains to WCF <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" /> </webHttpEndpoint> </standardEndpoints> </system.serviceModel>

    Read the article

  • Deserializing JSON in WCF throws xml errors in .Net 4.0

    - by Syg
    Hi there. I'm going slidely mad over here, maybe someone else can figure out what's going on here. I have a WCF service exposing a function using webinvoke, like so: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "registertokenpost" )] void RegisterDeviceTokenForYoumiePost(test token); The datacontract for the test class looks like this: [DataContract(Namespace="Zooma.Test", Name="test", IsReference=true)] public class test { string waarde; [DataMember(Name="waarde", Order=0)] public string Waarde { get { return waarde; } set { waarde = value; } } } When sending the following json message to the service, { "test": { "waarde": "bla" } } the trace log gives me errors (below). I have tried this with just a string instead of the datatype (void RegisterDeviceTokenForYoumiePost(string token); ) but i get the same error. All help is appreciated, can't figure it out. It looks like it's creating invalid xml from the json message, but i'm not doing any custom serialization here. The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'RegisterDeviceTokenForYoumiePost'. Unexpected end of file. **Following elements are not closed**: waarde, test, root.</Message><StackTrace> at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)

    Read the article

  • How to specify allowed exceptions in WCF's configuration file?

    - by tucaz
    Hello! I´m building a set of WCF services for internal use through all our applications. For exception handling I created a default fault class so I can return treated message to the caller if its the case or a generic one when I have no clue what happened. Fault contract: [DataContract(Name = "DefaultFault", Namespace = "http://fnac.com.br/api/2010/03")] public class DefaultFault { public DefaultFault(DefaultFaultItem[] items) { if (items == null || items.Length== 0) { throw new ArgumentNullException("items"); } StringBuilder sbItems = new StringBuilder(); for (int i = 0; i Specifying that my method can throw this exception so the consuming client will be aware of it: [OperationContract(Name = "PlaceOrder")] [FaultContract(typeof(DefaultFault))] [WebInvoke(UriTemplate = "/orders", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "POST")] string PlaceOrder(Order newOrder); Most of time we will use just .NET to .NET communication with usual binds and everything works fine since we are talking the same language. However, as you can see in the service contract declaration I have a WebInvoke attribute (and a webHttp binding) in order to be able to also talk JSON since one of our apps will be built for iPhone and this guy will talk JSON. My problem is that whenever I throw a FaultException and have includeExceptionDetails="false" in the config file the calling client will get a generic HTTP error instead of my custom message. I understand that this is the correct behavior when includeExceptionDetails is turned off, but I think I saw some configuration a long time ago to allow some exceptions/faults to pass through the service boundaries. Is there such thing like this? If not, what do u suggest for my case? Thanks a LOT!

    Read the article

  • Why does the WCF 3.5 REST Starter Kit do this?

    - by Brandon
    I am setting up a REST endpoint that looks like the following: [WebInvoke(Method = "POST", UriTemplate = "?format=json", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] and [WebInvoke(Method = "DELETE", UriTemplate = "?token={token}&format=json", ResponseFormat = WebMessageFormat.Json)] The above throws the following error: UriTemplateTable does not support '?format=json' and '?token={token}&format=json' since they are not equivalent, but cannot be disambiguated because they have equivalent paths and the same common literal values for the query string. See the documentation for UriTemplateTable for more detail. I am not an expert at WCF, but I would imagine that it should map first by the HTTP Method and then by the URI Template. It appears to be backwards. If both of my URI templates are: ?token={token}&format=json This works because they are equivalent and it then appears to look at the HTTP Method where one is POST and the other is DELETE. Is REST supposed to work this way? Why are the URI Template Tables not being sorted first by HTTP Method and then by URI Template? This can cause some serious frustrations when 1 HTTP Method requires a parameter and another does not, or if I want to do optional parameters (e.g. if the 'format' parameter is not passed, default to XML).

    Read the article

  • wcf web service in post method, object properties are null, although the object is not null

    - by Abdalhadi Kolayb
    i have this problem in post method when i send object parameter to the method, then the object is not null, but all its properties have the default values. here is data module: [DataContract] public class Products { [DataMember(Order = 1)] public int ProdID { get; set; } [DataMember(Order = 2)] public string ProdName { get; set; } [DataMember(Order = 3)] public float PrpdPrice { get; set; } } and here is the interface: [OperationContract] [WebInvoke( Method = "POST", UriTemplate = "AddProduct", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json)] string AddProduct([MessageParameter(Name = "prod")]Products prod); public string AddProduct(Products prod) { ProductsList.Add(prod); return "return string"; } here is the json request: Content-type:application/json {"prod":[{"ProdID": 111,"ProdName": "P111","PrpdPrice": 111}]} but in the server the object received: {"prod":[{"ProdID": 0,"ProdName": NULL,"PrpdPrice": 0}]}

    Read the article

  • JQuery + WCF + HTTP 404 Error

    - by hangar18
    HI All, I've searched high and low and finally decided to post a query here. I'm writing a very basic HTML page from which I'm trying to call a WCF service using jQuery and parse it using JSON. Service: IMyDemo.cs [ServiceContract] public interface IMyDemo { [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] Employee DoWork(); [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] Employee GetEmp(int age, string name); } [DataContract] public class Employee { [DataMember] public int EmpId { get; set; } [DataMember] public string EmpName { get; set; } [DataMember] public int EmpSalary { get; set; } } MyDemo.svc.cs public Employee DoWork() { // Add your operation implementation here Employee obj = new Employee() { EmpSalary = 12, EmpName = "SomeName" }; return obj; } public Employee GetEmp(int age, string name) { Employee emp = new Employee(); if (age > 0) emp.EmpSalary = 12 + age; if (!string.IsNullOrEmpty(name)) emp.EmpName = "Server" + name; return emp; } WEb.Config <system.serviceModel> <services> <service behaviorConfiguration="EmployeesBehavior" name="MySample.MyDemo"> <endpoint address="" binding="webHttpBinding" contract="MySample.IMyDemo" behaviorConfiguration="EmployeesBehavior"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="EmployeesBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="EmployeesBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> MyDemo.htm <head> <title></title> <script type="text/javascript" language="javascript" src="Scripts/jquery-1.4.1.js"></script> <script type="text/javascript" language="javascript" src="Scripts/json.js"></script> <script type="text/javascript"> //create a global javascript object for the AJAX defaults. debugger; var ajaxDefaults = {}; ajaxDefaults.base = { type: "POST", timeout : 1000, dataFilter: function (data) { //see http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/ data = JSON.parse(data); //use the JSON2 library if you aren’t using FF3+, IE8, Safari 3/Google Chrome return data.hasOwnProperty("d") ? data.d : data; }, error: function (xhr) { //see if (!xhr) return; if (xhr.responseText) { var response = JSON.parse(xhr.responseText); //console.log works in FF + Firebug only, replace this code if (response) alert(response); else alert("Unknown server error"); } } }; ajaxDefaults.json = $.extend(ajaxDefaults.base, { //see http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ contentType: "application/json; charset=utf-8", dataType: "json" }); var ops = { baseUrl: "/MyService/MySample/MyDemo.svc/", doWork: function () { //see http://api.jquery.com/jQuery.extend/ var ajaxOptions = $.extend(ajaxDefaults.json, { url: ops.baseUrl + "DoWork", data: "{}", success: function (msg) { console.log("success"); console.log(typeof msg); if (typeof msg !== "undefined") { console.log(msg); } } }); $.ajax(ajaxOptions); return false; }, getEmp: function () { var ajaxOpts = $.extend(ajaxDefaults.json, { url: ops.baseUrl + "GetEmp", data: JSON.stringify({ age: 12, name: "NameName" }), success: function (msg) { $("span#lbl").html("age: " + msg.Age + "name:" + msg.Name); } }); $.ajax(ajaxOpts); return false; } } </script> </head> <body> <span id="lbl">abc</span> <br /><br /> <input type="button" value="GetEmployee" id="btnGetEmployee" onclick="javascript:ops.getEmp();" /> </body> I'm just not able to get this running. When I debug, I see the error being returned from the call is " Server Error in '/jQuerySample' Application. <h2> <i>HTTP Error 404 - Not Found.</i> </h2></span> " Looks like I'm missing something basic here. My sample is based on this I've been trying to fix the code for sometime now so I'd like you to take a look and see if you can figure out what is it that I'm doing wrong here. I'm able to see that the service is created when I browse the service in IE. I've also tried changing the setting as mentioned here Appreciate your help. I'm gonna blog about this as soon as the issue is resolved for the benefit of other devs Thanks -Soni

    Read the article

  • Access Request Body in a WCF RESTful Service

    - by urini
    Hi, How do I access the HTTP POST request body in a WCF REST service? Here is the service definition: [ServiceContract] public interface ITestService { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "EntryPoint")] MyData GetData(); } Here is the implementation: public MyData GetData() { return new MyData(); } I though of using the following code to access the HTTP request: IncomingWebRequestContext context = WebOperationContext.Current.IncomingRequest; But the IncomingWebRequestContext only gives access to the headers, not the body. Thanks.

    Read the article

  • Http Post Format for WCF Restful Service

    - by nextgenneo
    Hey, super newbie question. Consider the following WCF function: [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class Service1 { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); [WebInvoke(UriTemplate = "", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare) ] public SomeObject DoPost(string someText) { ... return someObject; In fiddler what would my request headers and body look like? Thanks for the help.

    Read the article

  • MVC-style model binding in WCF?

    - by Mark
    I want to bind POSTed form values to parameters in my WCF operation in the same way that ASP.Net MVC allows me to do. So, for example if my form has "customer.Name" and "customer.Age" parameters, I want to make a standard HTML POST to a named endpoint/operation that takes a customer parameter and have it instantiated and populated like MVC can do... It looks like I can use WebInvoke and its UriTemplate property to map simple parameters - does anyone know if a more MVC-like model-binding way is possible? Thanks, Mark.

    Read the article

  • post object to wcf rest service

    - by gleasonomicon
    I'm using the WCF Rest service application project template in visual studio. I'm just learning about REST, and I was wondering how I would post a SampleItem object to the following method: [WebInvoke(UriTemplate = "", Method = "POST")] public SampleItem Create(SampleItem instance) { // TODO: Add the new instance of SampleItem to the collection throw new NotImplementedException(); } I get the general concepts of gets for the purposes of grabbing data, but I'm not sure how I would post the object in code (or just through a browser for testing) to the service.

    Read the article

  • Making a WCF call with AJAX

    - by DotnetDude
    Is it required to use a RESTful service to be able to make a ajax call to a wcf service (for example: by using WebInvoke attribute on Operation contracts) Once a service is made RESTful by adding a webHttp binding on the service host, can the host have other endpoints as well? (wsHttp or netTcp) Is it required that the aspNetCompatibilityEnabled be set to true for a service that has webHttp binding (and can this setting coexist for other endpoints) I understand I can use both JQuery and ScriptManager for making WCF calls on the client. Why should I use one over the other?

    Read the article

  • Formulate POST request in curl

    - by user1867256
    I'm using curl to send POST request to web service http ://localhost 2325//Service How can I desirialize body of the POST request into a variable which I could then access within my POST method ? Can someone give me an example? This is my method [WebInvoke(RequestFormat = WebMessageFormat.Json, UriTemplate = "/user", Method = "POST")] public void Create(User us) Class User contains user_id and user_name. Can anyone please help? All I need is an example how to formulate POST request in curl Thanks

    Read the article

  • Enable POST on IIS 7

    - by user26712
    Hello, I have a WCF service that requires POST verb. This service is hosted in a ASP.NET application on IIS 7. I have successfully confirmed that GET works, but POST does not. I have the following two operations, GET works, POST does not. [OperationContract] [WebInvoke(UriTemplate = "/TestPost", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public string TestPost() { return "great"; } [OperationContract] [WebGet(UriTemplate = "/TestGet", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public string TestGet() { return "great"; } When I try to access TestPost, I receive a message that says: "Method not allowed". Can someone help me configure IIS 7 to allow POST requests? Thank you!

    Read the article

  • 405 Method Not Allowed Error in WCF

    - by DotnetDude
    Can someone spot the problem with this implementation? I can open it up in the browser and it works, but a call from client side (using both jquery and asp.net ajax fails) Service Contract [OperationContract(Name = "GetTestString")] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json )] string GetTestString(); In Web.config among other bindings, I have a webHttp binding <endpoint address="ajax" binding="webHttpBinding" contract="TestService" behaviorConfiguration="AjaxBehavior" /> EndPoint Behavior <endpointBehaviors> <behavior name="AjaxBehavior"> <enableWebScript/> </behavior> </endpointBehaviors> </behaviors> Svc file <%@ ServiceHost Service="TestService" %> Client var serviceUrl = "http://127.0.0.1/Test.svc/ajax/"; var proxy = new ServiceProxy(serviceUrl); I am then using the approach in http://www.west-wind.com/weblog/posts/324917.aspx to call the service

    Read the article

  • Additional/Optional query string parameters in URI Template in WCF

    - by Rajesh Kumar
    I have written a simple REST Service in WCF in which I have created 2 method using same URI Template but with different Method(POST and GET). For GET method I am also sending additional query parameters as follows: [WebInvoke(Method = "POST", UriTemplate = "users")] [OperationContract] public bool CreateUserAccount(User user) { //do something return restult; } [WebGet(UriTemplate = "users?userid={userid}&username={userName}")] [OperationContract] public User GetUser(int userid, string userName) { // if User ID then // Get User By UserID //else if User Name then // Get User By User Name //if no paramter then do something } when I call CreateUserAccount with method POST it is working fine but when I call GetUser method using GET and sending only one query string parameter(userID or UserName) it is giving error "HTTP Method not allowed" but if send both parameters its wokrs fine. Can anyone help me?

    Read the article

  • Serializing an object into the body of a WCF request using webHttpBinding

    - by Bert
    I have a WCF service exposed with a webHttpBinding endpoint. [OperationContract(IsOneWay = true)] [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/?action=DoSomething&v1={value1}&v2={value2}")] void DoSomething(string value1, string value2, MySimpleObject value3); In theory, if I call this, the first two parameters (value1 & value 2) are taken from the Uri and the final one (value3) should be deserialized from the body of the request. Assuming I am using Json as the RequestFormat, what is the best way of serialising an instance of MySimpleObject into the body of the request before I send it ? This, for instance, does not seem to work : HttpWebRequest sendRequest = (HttpWebRequest)WebRequest.Create(url); sendRequest.ContentType = "application/json"; sendRequest.Method = "POST"; using (var sendRequestStream = sendRequest.GetRequestStream()) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(MySimpleObject)); jsonSerializer.WriteObject(sendRequestStream, obj); sendRequestStream.Close(); } sendRequest.GetResponse().Close();

    Read the article

  • JQuery and WCF - GET Method passes null

    - by user70192
    Hello, I have a WCF service that accepts requests from JQuery. Currently, I can access this service. However, the parameter value is always null. Here is my WCF Service definition: [OperationContract] [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public string ExecuteQuery(string query) { // NOTE: I get here, but the query parameter is always null string results = Engine.ExecuteQuery(query); return results; } Here is my JQuery call: var searchUrl = "/services/myService.svc/ExecuteQuery"; var json = { "query": eval("\"test query\"") }; alert(json2string(json)); // Everything is correct here if (json != null) { $.ajax({ type: "GET", url: searchUrl, contentType: "application/json; charset=utf-8", data: json2string(json), dataType: "json" }); } What am I doing wrong? It seems odd that I can call the service but the parameter is always null. Thank you

    Read the article

  • Different return XML in a WCF Operation

    - by Sean Hederman
    I am writing a service to a international HTTP standard, and there is one method that can return three different XML results, call them Single, Multiple and Error. Now I've written an IXmlSerializable class that can consume each of these results and generate them. However, WCF seems to insist that I can only have a single return XML root name. I have to choose an XmlRoot for my custom object of either Single, Multiple or Error. How can I set up WCF so that I can choose at runtime what the root will be? This is what I have currently. /// <summary> /// A collection of items. /// </summary> [XmlRoot("Multiple", Namespace = "DAV:")] public sealed class ItemCollection : IEnumerable<Item>, IXmlSerializable /// <summary> /// Processes and returns the items. /// </summary> [WebInvoke(Method = "POST", UriTemplate = "{*path}", BodyStyle = WebMessageBodyStyle.Bare)] [OperationContract] [XmlSerializerFormat] ItemCollection Process(string path);

    Read the article

  • Windows Azure access POST data

    - by Mohamed Nuur
    Ok, so I can't seem to find decent Windows Azure examples. I have a simple hello world application that's based on this tutorial. I want to have custom output instead of JSON or XML. So I created my interface like: [ServiceContract] public interface IService { [OperationContract] [WebInvoke(UriTemplate = "session/create", Method = "POST")] string createSession(); } public class MyService : IService { public string createSession() { // get access to POST data here: user, pass string sessionid = Session.Create(user, pass); return "sessionid=" + sessionid; } } For the life of me, I can't seem to figure out how to access the POST data. Please help. Thanks!

    Read the article

  • How do I construct a request for a WCF http post call?

    - by James Hay
    I have a really simple service that I'm messing about with defined by: [OperationContract] [WebInvoke(UriTemplate = "Review/{val}", RequestFormat = WebMessageFormat.Xml, Method = "POST", BodyStyle=WebMessageBodyStyle.Bare)] void SubmitReview(string val, UserReview review); UserReview is, at the moment, a class with no properties. All very basic. When I try and test this in Fiddler I get a bad request status (400) message. I'm trying to call the service using the details: POST http://127.0.0.1:85/Service.svc/Review/hello Headers User-Agent: Fiddler Content-Type: application/xml Host: 127.0.0.1:85 Content-Length: 25 Body <UserReview></UserReview> I would think i'm missing something fairly obvious. Any pointers?

    Read the article

1 2 3  | Next Page >