Encountering a 405 error while attempting to use WCF in conjunction with JSON

Attempting to create a WCF service that can handle JSON data for use in AJAX calls. Facing an issue where a 405 (Method Not Allowed) error occurs when trying to call the service from JavaScript. It appears that the server responds with this status code due to an OPTIONS method call made by the web page.

Service definition:

namespace JsonAjaxService
{
    [ServiceContract]
    public interface IService1
    {
       [OperationContract]
       [System.ServiceModel.Web.WebInvoke(
       Method = "POST",
       RequestFormat = WebMessageFormat.Json, 
       ResponseFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.Wrapped,
       UriTemplate = "testmethod")]
       CompositeType GetDataUsingDataContract(CompositeType composite);
    }

[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

Web.config:

<?xml version="1.0"?>
 <configuration>

  <appSettings>
  <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
  <compilation debug="true" targetFramework="4.5.1" />
  <httpRuntime targetFramework="4.5.1"/>
  </system.web>
  <system.serviceModel>
  <services>
  <service name="JsonAjaxService.Service1" behaviorConfiguration="ServiceBehaviour">
  <endpoint address ="" binding="webHttpBinding" contract="JsonAjaxService.IService1"      behaviorConfiguration="web">
  </endpoint>
  </service>
  </services>
  <behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
    <behavior name="ServiceBehaviour">
     <serviceMetadata httpGetEnabled="true"/>
     <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>

<directoryBrowse enabled="true"/>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>
</system.webServer>

</configuration>

JavaScript code to call the service:

function test() {
    var json = '{"StringValue":"test","BoolValue":"false"}';
    $.ajax(
    {
        type: "POST",
        processData: false,
        contentType: "application/json",
        url: "http://localhost:49572/Service1.svc/testmethod",
        data: json,
        dataType: "json",
        success: function (data) { alert(data); },
        error: function (data) { alert('error'); }
    });

Answer №1

Is your website hosted on the same domain? If not, consider using "jsonp" as the dataType instead

Answer №2

Consider the idea mentioned in the earlier response regarding jsonp. If that doesn't resolve the issue, attempt including it within "customHeaders"

<add name="Access-Control-Allow-Methods" value="GET,POST" />

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

Is the WebMethod function malfunctioning within an ASP.Net Web Role using Web Forms?

Issue Reproduction Steps: To replicate the issue, follow these steps: Open Visual Studio 2013 and create a new project by selecting "Azure Cloud Service" under File > New. Add an "ASP.NET Web Role" to the project named WebRole1. Choose the "Web Forms" ...

What methods can be used to measure the real-time utilization of the SQL Server client side connection pool?

When working with my C# code and using SqlConnection to connect to SQL Azure, I sometimes encounter an issue that results in the following error message: System.InvalidOperationException Timeout expired. The timeout period elapsed prior to obtaining a con ...

Can a React element be rendered multiple times without any issues?

Imagine a scenario where a functional component is responsible for displaying 5 icons. This task can be accomplished in the following way: export default const Icons = () => <div> <Icon/> <Icon/> <Icon/ ...

Retrieving JSON information from a PHP log document

As a newcomer to php, I have a json file that contains the following data: {"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":3261950 ...

What could be causing the warning message about 'bodyParser' being deprecated to appear on my screen?

Even though I used the most recent versions of both packages, I am still receiving a warning that 'bodyParser' is deprecated. It doesn't seem to affect my code, but I'm curious as to why this warning is appearing. const express = requi ...

Having difficulty accessing the attributes of an object within a property

I am encountering an issue when trying to access the properties of an object that contains a reference property of another object. Essentially, there is an object nested within another object. Upon fetching data from API calls like this one for instance:, ...

Having difficulty fetching the information from a JSON file and integrating it into Ionic

var app = angular.module('Event', ['ionic']); app.controller('ExhibitionTabCtrl', ['$scope', '$http', function($scope,$http) { $http.get("data.json") .success(function (response) { ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

What is Angular's approach to handling elements that have more than one directive?

When an element in Angular has multiple directives, each specifying a different scope definition such as scope:false, scope:true, or scope:{}, how does the framework handle this complexity? ...

Arranging multiple Label and Input fields in HTML/CSS: How to create a clean and

I'm struggling with HTML and CSS, trying to figure out how to align multiple elements on a page. I've managed to line up all the rows on the page, but for some reason, the labels are appearing above the input fields when I want them to appear be ...

Is there a way to solve this problem by creating a loop for the code?

document.getElementById("output1").innerHTML = totalDistance + ", " + hours + ":" + minutes+", $" + cost; this code combines input values to create an output. I am currently facing an issue where I need to loop thi ...

"Exploring the world of Vue.js and videojs: refreshing the video

Is there a way to refresh the videojs in Vue (3)? Here is the code snippet I am currently using: <template> <video-js controls="true" preload="auto" ref="video_player" class="video-js vjs-big-play-centered&quo ...

Encountering a 500 error while trying to access the document page in a Next.js Vercel app after

I am facing an issue with my next.js app hosted on Vercel, where I keep receiving a 500 error when trying to load a specific page. Upon inspecting the Chrome dev tools, I noticed that the error occurs when attempting to access the /dashboard page. Despite ...

Is it possible to refresh a div on one .aspx page using content from another .aspx page?

Just beginning my journey with asp.net and currently tackling a project that involves two .aspx pages. Events.aspx: This page is where the site admin can update upcoming events and webinars using an available panel to input event title, date, information ...

The npm audit tool uncovers unexpected dependencies in your project

When running npm audit, I receive warnings along with strange dependencies in the form of random hexadecimal strings. These strings change every time I run npm audit and are the same for all packages mentioned in the audit report. How can I remove these o ...

Tips on implementing the "remember me" feature using the Amplify Auth Class:

I'm in the process of developing a unique authentication component for an application utilizing Vue and AWS Amplify. One feature I'm looking to implement is a checkbox that allows users to remember their device upon login, eliminating the need fo ...

Ajax request received no data from API

I have been facing an issue with my code where I am posting an email on an API URL using an HTML form and PHP code with an Ajax call. However, the response I am getting is empty. I need to display this response on the same page below the form. I am sharing ...

Why isn't the Ajax success function being triggered, despite the API request being successful?

I can't seem to figure out why my success function isn't triggering, instead only the error function gets executed. It's strange because everything seems to be working fine when I make a POST request to my API. Here is my JavaScript code: ...

There seems to be an issue with the way the dataframe is being converted

Here is the structure of my dataframe l: 0 1 Sepal Length Label (4.296, 5.2] setosa 39 0.866667 versicolor 5 0.111111 virginica 1 0.022222 (5.2, 6.1] setosa ...

What's the reason for seeing "1:powershell" in the terminal when using react.js?

Can anyone explain why the terminal shows "1:powershell" in react.js? https://i.sstatic.net/1LyHe.png https://i.sstatic.net/5K95B.png ...