Incorrect Request Method for WCF json POST Request Leads to 405 Error (Method Not Allowed)

Hey there, I'm facing an issue with using Microsoft Visual Studio to create a WCF web service. Everything runs smoothly within Visual Studio, but when I try to connect to the service from outside, it fails to establish a connection. At first, I encountered a cross-domain error which I resolved by modifying the webconfig file and sourcing values from an external HTML file. However, I am now unable to perform a POST request and receiving this specific error:

GET http://localhost:3281/UserService.svc/SetUser?callback=jQuery11020891759618…20%22usertype%22:%20%22%22,%20%22email%22%20:%20%22%22%20}&_=1386343306675 405 (Method Not Allowed)

Due to my limited English proficiency, I have included my code and source files for your review.

Here is my JavaScript snippet:

<script>

function btnSubmit() {
$.support.corps = true;



        $.ajax({
              crossDomain: true,
            cache: false,
            async: false,
            type: "POST",
            url: "http://localhost:3281/UserService.svc/SetUser",
            data: '{ "usertype": "' + $("#txtuserName").val() + '", "email" : "' + $("#txtuserEmail").val() + '" }',
            contentType: "application/json;charset=utf-8",
            dataType: "jsonp",

            success: function (r) { alert("Successfully Registered!!!"); },
            error: function (e) { alert(e.statusText); }
        });
    }

    function btnRetrieve() {
    $.support.corps = true;
        $.ajax({
              crossDomain: true,
            cache: false,
            async: false,
            type: "GET",  
            url: "http://localhost:3281/UserService.svc/GetUser",
            data: { name: $("#find").val() },
            contentType: "application/json;charset=utf-8",
            dataType: "jsonp",
            success: function (r) {
                if (r != null) $("#DisplayResult").html(r.Email);
                 else
                 $("#DisplayResult").html("Bilgi yok");
            },
            error: function (e) { alert(e.statusText); }
        });
    }



  </script>

And here's the content of my service:

namespace JQueryCallToWcf
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class UserService
    {
        // Create a List of User type and add temporary data. This List will be used a Fake Repository for Data Tranasaction. In real world we can replace this with EntityFramework or Linq2Sql Data Model for actual data transactions.

        public static List<User> lstUsers = new List<User>()
            {
                new User() { Name="Rami", Email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82d0e3efebc2d0e3efebace1edef">[email protected]</a>"},
                new User() { Name="Bill", Email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f1d3633331f1d363333713c3032">[email protected]</a>"},
                new User() { Name="Mark", Email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3be928198b3be92...
            };

        // We have two service methods - SetUser and GetUser, which sets and gets user from fake repository.

        [OperationContract]
        [WebInvoke(
            Method = "POST",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        public void SetUser(string usertype, string email)
        {
            lstUsers.Add(new User() { Name = usertype, Email = email });
        }

        [OperationContract]
        [WebGet(
            ResponseFormat = WebMessageFormat.Json)]
        public User GetUser(string name)
        {
            User op = lstUsers.Where(p => p.Name == name).FirstOrDefault();
            return op;
        }
    }

    // This is the User Class, holding properties for Name and email.

    [DataContract]
    public class User
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string Email { get; set; }
    }



}

I've also added this to my webconfig file for handling cross-domain requests:

 <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonp" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <services>
      <service name="JQueryCallToWcf.UserService">
        <endpoint address="" binding="webHttpBinding"
                  bindingConfiguration="webHttpBindingWithJsonp"
                  contract="JQueryCallToWcf.UserService"
                  behaviorConfiguration="webHttpBehavior"/>
      </service>
    </services>
  </system.serviceModel>

For a full look at my working solution file and the issue with posting from an external HTML file, please visit this link:

Answer №1

After implementing jsonp and adjusting the binding in my web.config file, everything is now functioning as expected.

If you want to give it a try, here's how you can do it:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
        <handlers>
            <remove name="OPTIONSVerbHandler" />
            <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="None" preCondition="bitness32" />
        </handlers>
  </system.webServer>

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

What is the best way to store multiple checkbox categories as an array in a JSON object within a React application

Currently, I am in the process of creating a page that allows users to create posts and select multiple categories. However, I have encountered an issue when sending data via a post request that involves multiple category objects. It seems that I am strugg ...

A guide to populating a Dropdown List in Angular2 with data from a JSON response

I am facing an issue where the data I receive from my web server is showing up as undefined when trying to bind it into my front-end application. The array seems to be populated with the correct number of objects, and the data is binding to the component b ...

The use of fs.writeFileSync is invalid and will not work for this operation

Encountering an issue while working with fs in next.js, receiving the following error message: TypeError: fs.writeFileSync is not a function Here's a snippet from my package.json: resolve: { fallback: { "fs": false }, } ...

Utilizing JFlex for efficient brace matching

Currently, I am in the process of developing an IntelliJ plugin. One of the key features that I am working on is a brace matcher. After completing the JetBrains plugin tutorial, I was able to get the brace matcher functioning using this regular expression ...

Set up an array data by extracting values from an array prop within a Vue component

Within my Vue component, I am dealing with an array prop called selectedSuppliers that consists of objects. My goal is to set up a data property named suppliers and initialize it with the values from selectedSuppliers. However, I do not want any modificati ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...

Robotic Arm in Motion

GOAL: The aim of the code below is to create a robotic arm that consists of three layers (upper, lower, and middle), all connected to the base. There are four sliders provided to independently move each part except for the base which moves the entire arm. ...

What is the speed of communication for Web Worker messages?

One thing I've been pondering is whether transmission to or from a web worker could potentially create a bottleneck. Should we send messages every time an event is triggered, or should we be mindful and try to minimize communication between the two? ...

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

Is it possible to remove the browsing history of user inputs in JavaScript?

I'm currently working on a Simon Says game where the level of difficulty increases as players correctly repeat the pattern. However, I encountered an issue with clearing the input history that shows previous patterns entered by the user. How can I res ...

How can I incorporate a child component into a separate component within Angular version 14?

Currently working with Angular 14 and facing a challenge with including a child component from another module into a standalone component. The structure of the standalone component is as follows: <div> <child-component></child-component& ...

What is the best way to fill cascading dropdown lists with data fetched through ajax requests?

I attempted to create a CRUD web page with two cascading dropdown lists. Everything works smoothly when saving the data, but when retrieving it, the second dropdown list remains empty. Even after trying to populate the second dropdown list once the code i ...

Navigating JSON data to retrieve a specific property in AngularJS using a select form

Struggling with AngularJS and JSON. I have a form.html view where users can select their province. I have a Province JSON file for the select tag, but when storing in MySQL, I need the province Id. I tried using ng-value="province.id" in the option tag but ...

A guide on linking a jQuery dialog to an HTML element once the data has been updated with an AJAX response

On my PHP page, I have implemented a jQuery script to open a dialog window. The code for this is as follows: <script type="text/javascript"> $(document).ready(function() { var $loading = $('<img src="loading.gif" ...

Steps for calling a function in index.js using Node.js

I am just starting to learn about NodeJS and I have a question that might seem basic to some, but I would really appreciate some assistance here. Here is the content of my index.js file:- 'use-strict'; const { myauth } = require('./src/au ...

How to Apply a CSS Class to the Body Tag in Angular 2.x

How can I add [class.fixed]="isFixed" to the body tag when Angular 2.x is bootstrapped inside the body (outside my-app)? <html> <head> </head> <body [class.fixed]="isFixed"> <my-app>Loading...</my-app> </body> & ...

Managing large quantities of JSON-like data within MongoDB

My choice to use MongoDB is driven by the fact that Meteor doesn't officially support any other databases. The ultimate objective is to upload CSV files, parse them within Meteor, and import the data into the database. The size of the inserted data ...

Searching for a point within a specified range using Sequelize

I have a model called Location with a field named coordinates of type geometry. I'm looking to create a function that takes in latitude, longitude, and radius as parameters, and returns all locations within that radius (in meters). I attempted to foll ...

Guide on updating a text value using AJAX to request a PHP file without the need to refresh the webpage

Exploring the world of AJAX, I have a desire to develop a basic web application to apply my newfound knowledge practically. My goal is to calculate various percentages based on user input, and display the results on the webpage instantly using AJAX, witho ...

the 'class' keyword cannot be utilized in ECMA6

I attempted to execute a class in ECMA2015 but encountered the following error: class Task { constructor(name) { this.name=name; this.completed = false; }; } I received the error below: class Task { ^^^^^ SyntaxError: Unexpected reserved word} Not ...