Facing Content-type problem when sending data to WCF service using AngularJS

Apologies for the lengthy content, but I wanted to provide as much detail as possible. I am currently working on my first TypeScript/Angular application and trying to connect to our existing IIS WCF services which are cross-domain. Any input would be greatly appreciated.

Service Contract:

[OperationContract]
[WebInvoke(Method = "POST",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    UriTemplate = "LoginUser", 
    BodyStyle = WebMessageBodyStyle.Wrapped)]
LoginResponse LoginUser(LoginRequest request);

TypeScript Request:

class LoginRequest implements ILoginRequest {
    UserName: string;
    Password: string;
    ReturnListOfQueues: boolean;
}

Angular/TypeScript Login Method:

loginUser(UserName: string,
    Password: string,
    DomainName: string,
    ReturnListOfQueues: boolean): ng.IPromise<ILoginResponse> {

        var base_url = 'http://[IP]/AuthenticationService.svc/rest/LoginUser';

        var request = new LoginRequest();
        request.UserName = UserName;
        request.Password = Password;
        request.ReturnListOfQueues = ReturnListOfQueues;

        var req = {
            method: 'POST',
            url: base_url,
            headers: { 'Content-Type': undefined },
            data: JSON.stringify({ request: request }),
            contentType: "application/json",
            dataType: "json",
        }


        return this.$http(req)
            .then((response: ng.IHttpPromiseCallbackArg<ILoginResponse>): ILoginResponse=> {
            return <ILoginResponse>response.data;
            });
}

When attempting the above with

headers: { 'Content-Type': undefined }
, the JSON appears in Fiddler but the Content-Type is 'text/plan' resulting in a 400 Request Error.

I am unable to upload images at the moment, so here is a link to a screenshot of Fiddler:

If I manually change the Content-Type to application/json in Fiddler, the service call is successful and the expected response data is received.

However, once the request is updated to use application/json, the data no longer shows up in Fiddler.

var req = {
    method: 'POST',
    url: base_url,
    headers: { 'Content-Type': "application/json" },
    data: JSON.stringify({ request: request }),
    contentType: "application/json",
    dataType: "json",
}

Fiddler screenshot2:

CORS messages also appear in Firefox when setting the Content-Type attribute.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [removed]. (Reason: CORS preflight channel did not succeed). 

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [removed]. (Reason: CORS request failed).

web.config entries for the service

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type, Accept" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Max-Age" value="1728000" />
    </customHeaders>
</httpProtocol>

    <behavior name="restBehavior">
        <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"  automaticFormatSelectionEnabled="false" />

    </behavior>

UPDATE: I followed the instructions in this post blogs.microsoft.co.il/idof/2011/07/02/cross-origin-resource-sharing-cors-and-wcf/

Now, when sending the request with

headers: { 'Content-Type': "application/json" }
, I no longer receive the 405 error. It sends the OPTIONS request, which returns a 200 OK, but the POST request is never initiated.

Answer №1

Is it possible that the issue is stemming from JSON.stringify generating invalid JSON, leading to the submission of incorrect JSON data?

When attempting to Deserialize the Request body shown in your initial image, I encountered this error:

Error parsing boolean value. Path 'request.ReturnListOfQueues', line 1, position 80.

The code snippet used for this process was:

JsonConvert.DeserializeObject("{\"request\": {\"UserName\": \"admin\", \"Password\": \"admin\",\"ReturnListOfQueues\":false\"}}");

Upon correction to:

JsonConvert.DeserializeObject("{\"request\": {\"UserName\": \"admin\", \"Password\": \"admin\",\"ReturnListOfQueues\":\"false\"}}");

everything worked as expected. (An additional double quotation mark was inserted before false.)

Answer №2

After testing the app on chrome, I encountered an error message stating:

The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed

To resolve this issue, I decided to remove a specific section from the web.config file. This simple adjustment was enough to fix the problem. Additionally, Angular was able to successfully make the follow-up POST request after the pre-flight OPTIONS call.

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type, Accept" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
        <add name="Access-Control-Max-Age" value="1728000" />
    </customHeaders>
</httpProtocol>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pattern matching for locating content enclosed within parentheses

Looking for help with extracting a specific line of code: <link href="<%= Page.ResolveClientUrl("~/Styles/CAR.css") %>" rel="stylesheet" type="text/css" /> I need to isolate ~/Styles/CAR.css from the code above. Can anyone provide me with the ...

Effortlessly move and release Internet Explorer

Encountering drag and drop issues in Internet Explorer and Safari, while functioning correctly in Firefox 15 (untested on other versions). Dragging and dropping items between dropzones works in Safari, but sorting does not. In Internet Explorer, nothing wo ...

HTML page not being displayed in the AngularJS $routeProvider within the <div ng-view> tag

I'm a beginner in AngularJS and seeking assistance with resolving an issue related to routing to another HTML page while passing a parameter. My application consists of a form with input fields for name & course. The user's inputted information w ...

Is it possible to have separate click functions for the onclick attribute and jQuery click handler on an anchor tag, instead of just calling one function through onclick?

Attempting to implement multiple click handlers for an anchor tag: one using the "Onclick" attribute handler and the other using a jQuery click handler. This excerpt is from my HTML file. <html> <head> <script src="http://code.jquery.com ...

Maintaining Index as the default view in ASP.NET MVC 4

A standard MVC 4 application comes with predefined routes located in ProjectFolder\App_Start\RoutConfig.cs: routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", i ...

Strategies for dealing with inconsistencies in Gson serialization when utilizing generic wildcards

Consider the following scenario: static class MainBean { String mainField = "main"; } static class SubBean extends MainBean { String subField = "sub"; } static class MainBeanContainer { List <? extends MainBean> beans; p ...

AFNetworking failed to correctly deserialise a JSON-encoded dictionary within another dictionary

While working on my PHP backend, I have a situation where I am returning JSON data in the following format: $results_array=array(); $stmt->bind_result($IdUser,$username); while($stmt->fetch()) { $r ...

"Troubleshooting the issue of addEventListener failing to work in conjunction

window.addEventListener("onbeforeunload",function() {return "are you sure?"}); Unfortunately, the above code doesn't seem to be functioning as intended. The confirmation box is not being displayed and the page closes without any prompts. While I am ...

Ways to take a screenshot without relying on the user32.dll file, which contains unmanaged code

Need Help with Screenshots I am attempting to capture a screenshot from an external application and display the image in a .NET PictureBox. Avoiding user32.dll While there are many examples using user32.dll, I am seeking a solution for .NET that does not ...

Setting up jsLoader in the most recent version of angular's ocLazyLoad is a straightforward process

Previous iterations of angular oclazyload offered the ability to set up asyncLoader to utilize webpack bundle loader as its script loader. app.config(['$ocLazyLoadProvider', function ($ocLazyLoadProvider) { $ocLazyLoadProvider.config({ ...

What is the best way to apply a border-radius to the top of bars in @nivo/bar?

Is it possible to apply a border radius to the tops of each stack in a stacked responsive bar created from the Nivo library, without affecting the bottom? Currently, the responsive bar's border radius applies to both the top and bottom. Thank you! ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...

Using the JQuery template with $.get function does not produce the desired result

Working on populating a table using a Jquery Template can be tricky. One challenge is incorporating a json file via an ajax call for the population process. $(document).ready(function() { var clientData; $.get("/webpro/webcad/lngetusuario", funct ...

Tips for avoiding the influence of the parent div's opacity on child divs within a Primeng Carousel

I'm struggling to find a solution to stop the "opacity" effect of the parent container from affecting the child containers. In my code, I want the opacity not to impact the buttons within the elements. I have tried using "radial-gradient" for multipl ...

Exploring the world of Json and the art of

My JSON document contains strings that need to be translated. An example of this can be seen in my file, data.json: { "greeting": "trans:Hello" } In this scenario, the string "Hello" is identified as translatable by using the prefix "trans:" (although ...

Steps for extracting the specific index from a JSON array

Attempting to parse Json Data while retrieving it through a url using json and request. Sample Jason Data: {"statusMessage": "OK", "statusCode": 200, "response": { "id": "15015", "name": ...

Executing an Ajax request. Best method for transmitting various data elements:

I am currently attempting to perform an ajax call with multiple data inputs. When I send only one string of data, I use the following method: $.ajax({ url: "php/update_lastordning.php", type: "POST", data: "elId=" + elId }); To retrieve t ...

The Navbar is throwing a TypeError because it is unable to retrieve the property 'classList' of null

I am currently experimenting with building a navbar in HTML that has the capability to dynamically switch pages without changing links using href. The method I'm employing to achieve this involves adding a classList of is-active to the div elements wi ...

Ways to send information from Vue instance to nested components

Currently, I am fetching data using AJAX from the Vue instance and trying to pass it onto different components. As I delve deeper into learning Vue.js, I can't help but notice that the documentation seems a bit scattered... This snippet showcases wha ...

How can I populate a <select> tag with options dynamically using C# when the page loads?

I am using jQuery ajax to populate cascaded dropdown elements from a database. The issue I'm facing is that I can't seem to add the default "Select Program" option at the top of my first dropdown dynamically. Even though I tried using the prepend ...