POST access not permitted in REST service

After creating a REST service and successfully connecting to it using JQuery ajax with JSON data, I encountered an issue specifically when trying to use the POST method. For some reason, the service is not being triggered during a POST request.

The error message I received is as follows: XMLHttpRequest cannot load http://localhost:23262/GetAllDrawsShort. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:40464' is therefore not allowed access.

Interestingly, I have set the Access-Control-Allow-Origin header to allow all domains, yet the problem persists.

I researched similar issues and attempted suggested solutions without success.

Below is the code in Global.asax (Service):

    private void EnableCrossDmainAjaxCall()
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }

    }

And here's the Service class snippet:

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "GetAllDrawsShort", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
    public List<DrawShortObject> GetAllDrawsShort(string token, Guid userId)
    {
        if (Util.IsAuth(token))
        {
            return new DrawLogic().GetAllDrawsShort(userId);
        }
        else return null;
    }

Lastly, the JQuery code on the client page:

function GetAllDrawsShort() {
    var jData = {};
    jData.token = "123";
    jData.userId = "2f9e15d9-3654-4a43-89f4-07fea98a146f";

    return $.ajax({
        cache: false,
        type: "POST",        
        async: true,
        url: address + "GetAllDrawsShort",
        data: JSON.stringify(jData),
        contentType: "application/json",
        dataType: "json"
    });
};

Answer №1

Dealing with a similar issue, I managed to resolve it by utilizing jsonp as the dataType and generating a custom callback-wrapped response.

To begin, adjust your ajax request's dataType to 'jsonp'.

Next, construct your service response as follows:

string callback = HttpContext.Current.Request.QueryString["callback"];
string data = callback + "(" + yourJsonData + ")";
HttpContext.Current.Response.Write(data);

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

I am utilizing Vuex to store all of the product details and handle API request queries efficiently

Question regarding Vue/Vuex efficiency and best practices. I am working with an API that returns a paginated data-set of 50 products, which I am storing in a Vuex store. When displaying all products, I iterate over the Vuex store. Now, for individual pr ...

Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery $.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post' ,success:function (data) { console.log('ok'); }, ...

Utilize JavaScript to Trigger AJAX HoverMenuExtender in .NET

Within my C# web application, I am attempting to trigger an Ajax HoverMenuExtender using JavaScript, rather than relying on hovering over a designated control. When I set the TargetControlID of the HoverMenuExtender to a control on the page and hover ove ...

Implementing JavaScript to showcase a list extracted from an API dataset

I'm currently undertaking a project where I am integrating an API from a specific website onto my own webpage. { "data": [{ "truckplanNo":"TCTTV___0D010013", "truckplanType":"COLLECTION", " ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...

What is the best way to create a seamless Asynchronous loop?

Adhering to the traditional REST standards, I have divided my resources into separate endpoints and calls. The primary focus here revolves around two main objects: List and Item (with a list containing items as well as additional associated data). For ins ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

Challenges with handling JSON data in JavaScript

I am currently attempting to retrieve and parse JSON data in order to display it on a blank HTML file. Unfortunately, I keep encountering an issue where if I retrieve and parse the data, I receive an error stating Uncaught TypeError: Cannot read property & ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

Tips for preventing the use of nested functions while working with AJAX?

Consecutively making asynchronous calls can be messy. Is there a cleaner alternative? The issue with the current approach is its lack of clarity: ajaxOne(function() { // do something ajaxTwo(function() { // do something ajaxThree() }); }); ...

What other ways can websockets be utilized besides comet?

Websockets offer a more efficient solution for comet (reverse Ajax, often achieved through long-polling). However, are there other ways we can utilize websockets? For instance: - Can websockets be used to facilitate communication between different bro ...

What steps are involved in creating a video playlist with YouTube videos?

Is there a way to create a dynamic video playlist that supports embedded YouTube videos without refreshing the page? If a user clicks on another video, I want the video to change dynamically. You can check out this for an example. Do jPlayer, Video.js, Fl ...

Obtaining zip files using AngularJS

Upon entering the following URL in my browser, I am prompted to download a file: My goal is to download this file using an AngularJS HTTP request. I have created a factory for this purpose, but unfortunately, the download is not successful. Even though ...

Understanding the JSON output received from the Servlet

So, I have a Java Servlet set up to return JSON data in Application/JSON format using the GSON library. The GET method of the Servlet requires an ID parameter. When I send a request with BookingID as 1, Chrome shows the AJAX response like this: 0: {W ...

Creating a REST API with the POST method using Vanilla JavaScript/AJAX and encountering a 400 error (Bad request) issue

Could you assist me in figuring out how to utilize the POST method in vanilla JavaScript (without jQuery)? I've been attempting to do so with this code: var call = { "filterParameters": { "id": 18855843, "isInStockOnly": false, "newsOn ...

CoffeeScript:: I can't understand why the function body returns when using ajax

Hey there, I'm new to Coffeescript and have a question regarding Ajax. jQuery -> api = getId: -> res = [] $.ajax dataType: "jsonp" url: "http://localhost:3004/videos.json" success: (data) => ...

Prompt for confirmation in ASP.NET code-behind with conditions

I've searched around for a solution to this problem. Below is a representation of my pseudocode: bool hasData = ItemHasData(itemid); Confirm = "false"; // hidden variable if (hasData) { //Code to call confirm(message) returns "true" or "false" ...

PHP and AJAX allow for seamless data retrieval without the need for page refreshing, and the data can be easily displayed in a modal window

I am currently encountering an issue with sending data to another page without refreshing. I am able to send the data as text, but for some reason, I am unable to send it as a modal. Why might this be happening? Here is an image of my current page https:/ ...

Trouble with Google Interactive Charts failing to load after UpdatePanel refresh

Desperately seeking assistance! I have spent countless hours researching this issue but have hit a dead end. My dilemma involves using the Google Interactive Charts API within an UpdatePanel to dynamically update data based on dropdown selection changes. H ...

Exploring the differences between detecting the XMLHttpRequest object in JavaScript and using the try

When it comes to determining browser support for AJAX, I typically rely on object detection like this: if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } ...