怎么办AJAX POST跨域自定义页眉 [英] How to do AJAX POST cross-domain with custom headers

查看:88
本文介绍了怎么办AJAX POST跨域自定义页眉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找周围的一切结束了,我无法找到一个明确的答案。

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

我需要能够执行AJAX POST发送自定义标题。我可以完全控制这两个客户端脚本和服务器端的服务,因此,如果要我做任何调整到两侧,使这项工作,我能够做出这些改变。

I need to be able to perform an AJAX POST and send up custom headers. 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.

我目前使用jQuery的,但是如果jQuery是无法做到这一点,我需要使用另一个库,是不是在所有问题无论是。理想情况下我会preFER坚持一个库(jQuery的),但我更乐意使用第二个,如果它解决了我的问题。

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. 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.

目前我的code是这样的:

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);
    }
});

和不幸的jQuery甚至没有尝试发送请求到服务器,但是当我删除头,它发出的请求。我真的尽管需要这些报头,所以任何帮助将是非常美联社preciated。

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. 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.

推荐答案

我不知道你是否还在寻找一种方式来做到这一点。这是可以做到。下面是一个简单的CORS处理程序

I dont 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);
        }
    }
}

一旦添加了这一点,那么在Application_Start方法中的Global.asax文件中注册处理程序

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

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

现在,您可以发送您的请求头。希望有所帮助。这已经过测试的Web API,MVC 4和谷歌Chrome和Firefox的网站。

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.

-Suj

这篇关于怎么办AJAX POST跨域自定义页眉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆