7

I have tried every combination to send a request to send a POST request to RESTful WCF from jQuery.

Can someone imitate and make it working. Code is here : http://pastebin.com/Ua97919C

I am working with WCF from past 2 years, but every time i send a POST request it makes me struggle a lot.

I am struggling to make it work from past 4 days and gone through atleast 35-40 posts.

Eventually, this request would be sent from iPhone to WCF.

When i check it with Fiddler the error mostly is: *The server encountered an error processing the request. The exception message is 'The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details. The exception stack trace is: at

System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)
   at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
TheBoyan
  • 6,802
  • 3
  • 45
  • 61
iMatoria
  • 1,450
  • 2
  • 19
  • 35

2 Answers2

4

Add a Global.ascx file in youe solution and replace the code with following

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}

one more thing chnage dataType:'text'

$.ajax({
    type: "POST",
    url: "http://localhost:4638/Edulink.svc/SaveUserData",                        
    dataType: "text",
    contentType: "application/json",
    data:'{"EmailID":"praveen", "LevelID": 1}',         
    success:function(data, status) {             
        console.log(data); //gives 1                
    },
    error:function(request, status, error) {
        alert("o0ops");           
    }
});
WrightsCS
  • 50,551
  • 22
  • 134
  • 186
Rafay
  • 30,950
  • 5
  • 68
  • 101
  • No..It throws error at jQuery.min.js then. I had tried that earlier as well. – iMatoria Dec 16 '11 at 17:22
  • Can you create a sample project and try it yourself. – iMatoria Dec 16 '11 at 17:31
  • Na that will not be feasible for me to do if you make a sample project and upload it send me a link i'll have a look at it `:)` – Rafay Dec 16 '11 at 17:34
  • How do i send you the project? You have dropbox account? – iMatoria Dec 16 '11 at 17:36
  • Here is the zip file: http://www.filefactory.com/file/c0dd2ac/n/WCFPost.zip. Please help me out. – iMatoria Dec 16 '11 at 18:17
  • @iMatoria if you want the sample prj tell me i'll upload it – Rafay Dec 16 '11 at 19:51
  • I tried adding Global file at both web & service project. At web project it sends the successful response but doesn't go to service because of HttpContext.Current.Response.End();. At Service project it doesn't make any effect. Can you please upload the sample project at filefactory.com – iMatoria Dec 17 '11 at 06:20
  • Thanks for the efforts. But, it still doesn't work. Request is successful but it doesn't go to the particular method, because response is been ended by Global.ascx HttpContext.Current.Response.End();. If i comment this complete function also, then i get 405 Method not allowed error. Did you recieve correct data from the Service method? – iMatoria Dec 17 '11 at 10:57
  • yes i did recieve the `1` returned by the method, and the Global file is to be added only in the `WCFPost.Service` project, here is the ajax call which i used with the service http://pastebin.com/2veXcN8Z – Rafay Dec 17 '11 at 11:03
  • hmm..I think then its my bad luck that its not working at my end. Anyways, thanks for all the efforts. Can't mark it as Correct Answer because it didn't work for me and could lead my profile into trouble, if i do. But, special thanks to you. – iMatoria Dec 17 '11 at 11:39
  • I have marked your response as the answer because you led me to the finding that its depends upon from where you initiate the request to WCF post. When i initiated request from jQuery it choose to be OPTIONS and not POST, because of some security reasons. But, it worked very fine when i initiated it from iPhone, which i eventually wanted. Thanks man. – iMatoria Dec 18 '11 at 18:19
2

The problem is the body style of the operation. You declared it as

[WebInvoke(
        Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        UriTemplate = "/SaveUserData")]
string SaveUserData(UserInfo userInfo);

meaning that the request must be wrapped in an object, with a member for the object name. If you send this request below, it should work.

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: url,
    data: '{"userInfo":{"EmailID":"praveen", "LevelID": 1}}',
    dataType: "json",
    processData: false,
    success: function (data, textStatus, jqXHR) {
        debugger;
    },
    error: function (jqXHR, textStatus, errorThrown) {
        debugger;
    }
});

Another alternative is to change the BodyStyle property of the operation to Bare, in which case your original request was correct.

carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
  • No it doesn't work either way. Can you download the sample and make it work: http://www.filefactory.com/file/c0dd2ac/n/WCFPost.zip – iMatoria Dec 16 '11 at 18:44
  • You can look at the sample I have at pastebin which is similar to your scenario, and make yours work. SVC file: SVC: http://pastebin.com/aG7FNDb0. SVC.cs file: SVC.CS: http://pastebin.com/vhqeBSV3. HTML file: http://pastebin.com/fDiYzR3Q. Web.config: http://pastebin.com/j4yw1axb – carlosfigueira Dec 16 '11 at 19:13
  • Thanks for the efforts. But, it still doesn't work. I have every piece of code like you stated. – iMatoria Dec 17 '11 at 06:22