Пост Ajax не работает в Firefox, но работает в Chrome - PullRequest
0 голосов
/ 11 апреля 2019

Я новичок в ReactJ. Я пытаюсь получить некоторые данные из записи webAPI AJAX

Мой код работает нормально в Chrome, но в Mozilla Fire Fox его не работает Если я удаляю раздел заголовков в $ .ajax, API вызывает его работоспособность, но с заголовком нет. Пожалуйста, помогите мне, что мне не хватает или как он будет работать в Firefox или Chrome.

в моем классе userTypeAPI.js

export const constgetUsertype = (authenticationKey) => {
    return getUsertype(authenticationKey);
};
$.support.cors = true;
function getUsertype(authenticationKey) {
    var returnvalue = '';
    $.ajax({
        url: usertypeURL + "/getUserType",
        type: "POST",
        async: false,
        beforeSend: function (xhr) {
            xhr.withCredentials = false;
        },
        xhrFields: {
            withCredentials: false
        },
        crossDomain: true,
        headers: {
            "AuthenticationKey": authenticationKey
        },
        //contentType: 'application/json',
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        success: function (data) {
            returnvalue = data.d;
        },
        error: function (request, error) {
            debugger;
            alert(error);
            returnvalue = "";
        }
    });
    return returnvalue;
}

В реаги.jsx класс

import * as userTypeAPI from '../UserTypeAPI';


    componentDidMount() {
        var usertypes = userTypeAPI.constgetUsertype(sessionStorage.getItem('AuthenticationKey'));

        this.setState({
            options: usertypes
        });
}

В контроллере webAPI код класса равен

 [RoutePrefix("api/UserType")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class UserTypeController : ControllerBase
    {
        TaskUserType taskUserType = new TaskUserType();

        [HttpPost]
        [ActionName("getUserType")]
        public object getUserType() //Parameter is EntityUserType because we pass UserType information for get list of task
        {
            try
            {
                var requestId = string.Empty;
                var AuthenticationKey = string.Empty;
                var re = Request;
                var headers = re.Headers;
                if (headers.Contains("AuthenticationKey"))
                {
                    AuthenticationKey = headers.GetValues("AuthenticationKey").First();
                }

                long userId = 0;

                if (!Authenticated(AuthenticationKey))
                    return Ok("Unauthorize user");
                else
                    userId = Convert.ToInt64(dtSession.FirstOrDefault().User_Id);

                Dictionary<string, object> returnDict = new Dictionary<string, object>();
                List<EntityUserType> lstUserTypes = new List<EntityUserType>();
                lstUserTypes = taskUserType.getAllUserTypes();
                returnDict = new Dictionary<string, object>();
                returnDict.Add("d", lstUserTypes);
                return returnDict;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
   }

А конфиг webAPI это

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Location, Lock-Token, If" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>

Я уже проверяю Пост $. Ajax работает в Chrome, но не в Firefox ссылка, но здесь она показывает event.preventDefault (); и в моем коде нет событий.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...