0
votes

I am trying to send a request to an API method using jQuery. Client side code is as follows:

$.ajax({
        type: 'POST',
        url: endpointLocation,
        headers: {
            AuthToken: "myTokenValue",            
            UserId: "12345"
        },
        timeout: 5000,
        dataType: 'json',
        data: {
        isActive: true,
        empId: 2050
        },
        success: function (result) {
            debugger;
        },
        error: function (xhr, textStatus, errorThrown) {
            debugger;
        }
    });

Web.config entries:

<handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>

I am getting an error "XMLHttpRequest cannot load http://domain/application/method/. Response for preflight has invalid HTTP status code 404" after this the control jumps to error method.

Also, if I add the headers I am sending in web.config file, it still makes no difference. This is how I tried to add headers in web.config:

<add name="Access-Control-Allow-Headers" value="Content-Type, AuthToken, UserId" />

I need to send these headers since the API endpoint implements custom authentication that takes values from header and verify the user. This can not be avoided.

Can someone please help me rectify the issue?

1

1 Answers

1
votes

Try to add following in Global.asax.cs file

 protected void Application_BeginRequest()
        {
            if (Context.Request.HttpMethod != "OPTIONS") return;
            Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
            Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,x-access-token");
            Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            Context.Response.End();
        }