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

Press the Text and Alter Text with React

I'm having an issue with the onClick event using React hooks. My goal is to have the text change to a different one when the user clicks, and then revert back to the original text on another click. For example, clicking "Change First" should switch it ...

Issue with storage functionality in Vuex Axios response

Every time I send data to the Vuex storage using an axios response, for example: ** Sidebar.vue ** created(){ this.getRoles(); }, methods: { getRoles(){ var _this = this var roles = null this.$http.get('/api/userroles/ ...

Tracing a path with a snapping motion using my thumb

Before we begin, let's take a look at the example below. The functionality of this component should mimic that of an input type range. However, I am facing some challenges in calculating the step value and snapping the thumb onto the trail based on t ...

Utilizing AngularJS to include information into JSON-LD

As a newcomer to AngularJS, I find myself stuck in one of my projects. My goal is to convert the user-entered data in a form into the format: << "schema:data" >> and then push and display it within the @graph of the json-ld. Here are my HTML an ...

Perform an asynchronous request using a data variable retrieved from a previous asynchronous request

I have a function using ajax to parse XML data. Here is an example: $.ajax({ type: "GET", url: "the.xml", dataType: "xml", success: function parseXml(data){ $(data).find("ITEM").each(function(){ var x = $("URL", this).t ...

Ensuring the safety of ajax GET/POST communication between client and server

Let's say I'm working with a specific API and my file server.php is responsible for connecting to the API service. On the client side, I am using an AJAX call like this: $http({ url : 'server/server.php', method : &ap ...

Error on Network: 400 BAD REQUEST in Ionic framework

I recently implemented push notifications successfully, but I am facing a network error with a 400 bad request when trying to access a specific API endpoint. The error message states: "NetworkError: 400 BAD REQUEST - https://apps.ionic.io/api/v1/app/77c3 ...

Switch out the content when the button is clicked

Seeking a code snippet to enable clicking a button (Button labeled "Next") for replacing existing code on the page with new code. Current code below should be replaced, starting from the score counter section. Please excuse any messy code as I'm new a ...

Parsing JSON data using Newtonsoft.Json library to convert it into a List collection with named entries

I need help deserializing this JSON data set: { "Home1": [ { "name": "Hans", "age": 20 }, {...} ], "Home2": [ {...}, {...} ] } I want to map it into a collection of ...

Exploring the principles of updating a table in SQL Server

I am working on an asp.net web application where users are able to update a table in the database. I am seeking guidance on the appropriate method to achieve this. The image provided illustrates that the red shaded area contains data that is common and doe ...

The SelectedIndexChanged event fails to trigger following an onchange event

I am currently working on validating a dropdown list on the client side based on its selected index/value. My goal is to create a function that triggers an alert when the selected index is 0, or alternatively execute the SelectedIndexChandged method in the ...

Sinon's fakeTimers failing to trigger

I'm encountering an issue with sinon's fakeTimers while working in a setup that includes Marionette.js, underscore, and chai test runner. Strangely, when I place a breakpoint in Chrome and step through the code, my timer functions as expected. Ho ...

Implementing the rotation of an element using 'Transform: rotate' upon loading a webpage with the help of Jquery, Javascript, and

A div element designed to showcase a speedometer; <div class="outer"> <div class="needle" ></div> </div> The speedometer animates smoothly on hover; .outer:hover .needle { transform: rotate(313deg); transform-origin: ce ...

Failure of Ajax request in NodeJS

I've been encountering an issue while attempting to submit a form from the client to Express. Every time I try, I receive the following error message: Cannot POST /request_method Here is the code snippet that I am using: index.html <form i ...

A step-by-step guide on how to fill a Vuetify select box with data retrieved from

I'm currently working on populating a select box in Vuetify by retrieving data through an ajax call. I'm struggling to figure out how to populate the select box with this data. The ajax call is successful and I receive an array of objects which I ...

Develop a TypeScript class in a distinct file

I currently have ag-grid implemented in an Angular project with a CustomFilter. The problem is that the file containing the code for the CustomFilter function is becoming quite large and difficult to manage. I am now looking to move the CustomFilter to a s ...

Error: JSON Exception - Value Not Found

Having some issues, as shown in the logcat below: D/JSON Parser: ����������µM @@ÿJÌYÁ5õfyo]"dÄM]wÅ] ÿ{kXôuí4ð�... ña,-8vbðp@botS â¯&©V ±4Ý~HÌBSBÓ N<sN{UÑãHIrR`ÊN´AÓ... E/JSON Parser:E ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...

Typescript raises a error notification regarding the absence of a semicolon when importing a JSON module

Attempting to import a local JSON object into my Vuex store using const tree = import('@/articles/tree.json');. The setting "resolveJsonModule": true, has been enabled in my tsconfig.json and it loads successfully, however NPM is flooding the out ...

Discover the process of connecting a REST controller with AngularJS and Spring

I have a list of file paths stored in an array within the scope variable of an AngularJS Controller. My goal is to properly map these file paths to a Java REST controller for further processing. When I pass it as "/ABC/Scope-Variable," it successfully ma ...