认沽权的CORS问题 [英] CORS issue on Put

查看:93
本文介绍了认沽权的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向我的Api发送看跌期权时,我首先得到方法OPTIONS和一个错误.然后,它再次命中我的select动作方法,其中包含看跌期权信息.

When i send a put to my Api i first get method OPTIONS and an error. It then hits my select action method again and it contains the put info.

  public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
        {
            var request = controllerContext.Request;
            if (request.IsInspectRequest())
            {
                var simulate = new ActionSelectSimulator();
                request.Properties[RequestHelper.ActionCache] = simulate.Simulate(controllerContext);
            }

            var selectedAction = _innerSelector.SelectAction(controllerContext);

            return selectedAction;
        }

我有一个处理我的飞行前请求的类.

I have a class that handles my preflight request.

   public class XHttpMethodOverrideHandler : DelegatingHandler
    {
        static readonly string[] httpOverrideMethods = { "PUT", "DELETE" };
        static readonly string[] accessControlAllowMethods = { "POST", "PUT", "DELETE" };
        static readonly string httpMethodOverrideHeader = "X-HTTP-Method-Override";
        static readonly string ORIGIN_HEADER = "ORIGIN";
        static readonly string accessControlAllowOriginHeader = "Access-Control-Allow-Origin";
        static readonly string accessControlAllowMethodsHeader = "Access-Control-Allow-Methods";
        static readonly string accessControlAllowHeadersHeader = "Access-Control-Allow-Headers";

        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            try
            {
                if (request.Method == HttpMethod.Post && request.Headers.Contains(httpMethodOverrideHeader))
                {
                    var httpMethod = request.Headers.GetValues(httpMethodOverrideHeader).FirstOrDefault();
                    if (httpOverrideMethods.Contains(httpMethod, StringComparer.InvariantCultureIgnoreCase))
                        request.Method = new HttpMethod(httpMethod);
                }

                var httpResponseMessage = base.SendAsync(request, cancellationToken);

                if (request.Method == HttpMethod.Options && request.Headers.Contains(ORIGIN_HEADER))
                {
                    httpResponseMessage.Result.Headers.Add(accessControlAllowOriginHeader, request.Headers.GetValues(ORIGIN_HEADER).FirstOrDefault());
                    httpResponseMessage.Result.Headers.Add(accessControlAllowMethodsHeader, String.Join(", ", accessControlAllowMethods));
                    httpResponseMessage.Result.Headers.Add(accessControlAllowHeadersHeader, httpMethodOverrideHeader);
                    httpResponseMessage.Result.StatusCode = HttpStatusCode.OK;
                }
                else if (request.Headers.Contains(ORIGIN_HEADER))
                    httpResponseMessage.Result.Headers.Add(accessControlAllowOriginHeader, request.Headers.GetValues(ORIGIN_HEADER).FirstOrDefault());

                return httpResponseMessage;
            }
            catch (Exception ex)
            {
                ILoggerService logger = IocContainer.Container.TryGetInstance<ILoggerService>();
                if (logger != null)
                {
                    logger.Error(ex);
                }
                return Task.FromResult<HttpResponseMessage>(request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }

我也已经添加到我的webconfig

I also have added to my webconfig

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

当我发送Put Ajax呼叫时,我收到一个错误.它命中了我的方法并执行了我的操作,但是它发送了一个错误.如果我通过邮递员发送看跌请求,那么我没有问题.如果我从客户端发送它,则会收到错误消息,因为它获得的第一种方法是{OPTIONS}.我想念什么? 这是我的Ajax放

When i send my Put Ajax call i receive an error. It hits my method and performs my action but it sends an error. If i send the put request via postman then i have no problem. If i send it from the client I get an error because the first method it gets is {OPTIONS}. What am i missing? Here is my Ajax put

  $.ajax({
                    url: "http://localhost:61148/api/mycontroller",
                    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                    async: true,
                    type: "PUT",
                    data: sendData,
                    datatype: 'json',
                    crossDomain: true,
                    success: function () {

推荐答案

我在其他几个问题中找到了答案.解决方案是如此简单,令人感到痛苦.如果遇到此问题,请在控制器中添加一个options方法.

I found the answer in a couple of other questions. The solution is so simple it hurts. If you're having this issue add an options method in your controller.

public HttpResponseMessage Options()
{
    var response = new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.OK
    };
    return response;
}

这篇关于认沽权的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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