简体   繁体   English

如何使用自定义标头进行AJAX POST跨域

[英]How to do AJAX POST cross-domain with custom headers

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. 我需要能够执行AJAX POST并发送自定义标头。 I have full control of both the client side script and the server side service, so if I have to make any tweaks to either side to make this work, I am able to make those changes. 我完全控制了客户端脚本和服务器端服务,因此如果我必须对任何一方进行任何调整以使其工作,我能够进行这些更改。

I am currently using jQuery, however if jQuery is unable to do this and I need to use another library that is not a problem at all either. 我目前正在使用jQuery,但是如果jQuery无法做到这一点,我需要使用另一个根本不是问题的库。 Ideally I would prefer to stick to a single library (jQuery) but am more than happy to use a second if it solves my problem. 理想情况下,我更喜欢坚持使用单个库(jQuery),但如果能解决我的问题,我会非常乐意使用它。

Currently my code looks like this: 目前我的代码如下所示:

$.ajax({
    type: 'POST',
    url: 'http://localhost:65079/TestHandler',
    crossDomain: true,
    data: myVariableOfData,
    dataType: 'json',
    beforeSend: function(xhr) {
        xhr.setRequestHeader('MessageId', 'abc123');
    },
    success: function(responseData, textStatus, messageId) {
        console.log("success");
    },
    error: function(responseData, textStatus, errorThrown) {
        console.log(textStatus);
        console.log(responseData);
        console.log(errorThrown);
    }
});

and unfortunately jQuery does not even attempt to send the request to the server, however as soon as I remove the headers, it sends the request. 不幸的是,jQuery甚至没有尝试将请求发送到服务器,但是一旦我删除了标头,它就会发送请求。 I really need these headers though, so any help would be highly appreciated. 我真的需要这些标题,所以任何帮助都将受到高度赞赏。

Please ask me any questions that may help resolve this issue and I will respond as fast and as I best as I can. 请问我任何可能有助于解决此问题的问题,我会尽快回复,尽我所能。

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 这是一个CORS处理程序示例

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 添加后,在Application_Start方法内的Global.asax文件中注册处理程序

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. 这已通过Web API,MVC 4以及Google Chrome和Firefox的网站进行了测试。

At the risk of totally sounding like Siri, it sounds like are looking for how to get CORS to work... 冒着听起来像Siri的风险,听起来好像正在寻找如何让CORS工作......

Here's a few resources that will hopefully help: 这里有一些资源可以提供帮助:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM