How to do AJAX POST cross-domain with custom headers

后端 未结 2 1948
你的背包
你的背包 2021-01-14 15:03

I have been looking around all over and I cannot find a definitive answer to this.

I need to be able to perform an AJAX POST and send up custom headers. I have full

相关标签:
2条回答
  • 2021-01-14 15:30

    At the risk of totally sounding like Siri, it sounds like are looking for how to get CORS to work...

    Here's a few resources that will hopefully help:

    • How to get a cross-origin resource sharing (CORS) post request working
    • Getting CORS Working
    • Cross-Origin Resource Sharing Demo
    • Cross-domain Ajax with Cross-Origin Resource Sharing
    0 讨论(0)
  • 2021-01-14 15:51

    I don't know if you are still looking for a way to do this. This can be done. Here is a sample CORS Handler

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Api.Handlers
    {
        /// <summary>
        /// 
        /// </summary>
        public class CorsHandler : DelegatingHandler
        {
            const string Origin = "Origin";
            const string AccessControlRequestMethod = "Access-Control-Request-Method";
            const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
            const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
            const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
            const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="request"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                bool isCorsRequest = request.Headers.Contains(Origin);
                bool isPreflightRequest = request.Method == HttpMethod.Options;
    
                if (isCorsRequest)
                {
                    if (isPreflightRequest)
                    {
                        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
    
                        string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                        if (accessControlRequestMethod != null)
                        {
                            response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                        }
    
                        string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
                        if (!string.IsNullOrEmpty(requestedHeaders))
                        {
                            response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                        }
    
                        TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                        tcs.SetResult(response);
                        return tcs.Task;
                    }
    
                    return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
                    {
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                        return resp;
                    });
                }
    
                return base.SendAsync(request, cancellationToken);
            }
        }
    }
    

    Once you add this, then register the handler in your Global.asax file inside the Application_Start method

    GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
    

    Now you can send your request headers. Hope that helps. This has been tested with Web API, MVC 4 and the site from Google Chrome and Firefox.

    0 讨论(0)
提交回复
热议问题