0

I have added [System.Web.Http.Cors.EnableCors(origins: "*", headers: "*", methods: "*")] before my public class UPWebsiteAPIController : ApiController and every time I want to POST data my function should return new JsonResult { Data = toReturn };. The thing is that this function is fully executed and returning toRerurn object, but browser gets error code 500 and

No Access-Control-Allow-Origin header is present to the requested resource

Backend code:

        [System.Web.Http.HttpPost]
    public async Task<System.Web.Mvc.ActionResult> CreateEvent(FormDataCollection formData)
    {
        try
        {
            (code which works fine)
            toReturn[0] = HttpStatusCode.OK;
            return new JsonResult { Data = toReturn };
        }
        catch (Exception ex)
        {
            toReturn[0] = HttpStatusCode.BadRequest;
            return new JsonResult { Data = toReturn };
        }
    }

Fronend code:

$.ajax({    
    type: "POST",
    url: 'http://www.XXX.aspnet.pl/api/UPWebsiteAPI/CreateEvent',
    data: data,
    beforeSend: function() {

      $loading.show();

    },

    success: function(response) {
        console.log('sukces');
        console.log(response);

        $loading.hide();
        $response.show();
        $response.find('.pay-button').show();
        $response.find('.pay-link').attr('href', response.Data[1]);

        $response.find('h2').html("Gratulacje!' );

    },
    error: function(response) {
        console.log('error');
        console.log(response);
        $loading.hide();
        $response.show();
        $('.pay-button').hide();
        $response.find('h2').html("Przepraszamy...");
    }
  });

What should I do? Funny thing is that is sometimes works without any problems and sometimes (more than often) gets those errors.

1 Answer 1

1

In your global.asax.cs file Add the below method.

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE,GET");

            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "content-type,Access-Control-Allow-Origin,authToken, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

It didn't help me
are you using any token based authentication?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.