0

Есть сервис на сишарпе, который отдает js-скрипту json строку. Использую библиотеку Newtonsoft.Json. Но в моей реализации сервис оборачивает json в тег <string></string>, что, соответственно, мне мешает нормально работать с ним на клиенте. Как можно от него избавиться?

JS-код:

function VerifySignature() {
            var keyInfo = GetKeyInfo();
            // отправляем данные в контроллер для валидации сертификата
            $.ajax({
                type: "POST",
                url: "VerifySignatureService.asmx/VerifySignature",
                data: { certInfo: JSON.stringify(keyInfo) },
                success: function (result) {
                    alert(result);
                    console.log(result);
                }
            });
        }

C#-код:

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class VerifySignatureService : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public string VerifySignature(string certInfo)
        {
            ResponseType response = new ResponseType();
            if (string.IsNullOrEmpty(certInfo) || certInfo == "[]")
            {
                response.isError = true;
                response.isValid = false;
                response.message = "Пришел пустой keyInfo";
                return JsonConvert.SerializeObject(response);
            }
            var keyInfo = JsonConvert.DeserializeObject<KeyInfo>(certInfo);
            if (CertificateVerifier.VerifyCertificateSign(true, keyInfo))
            {
                response.isError = false;
                response.isValid = true;
                response.message = Resources.SuccessfullySigned;
            }
            else
            {
                response.isError = false;
                response.isValid = false;
                response.message = "Ваш ключ не прошел проверку";
            }
            return JsonConvert.SerializeObject(response, Formatting.Indented);
        }
    }

    public class ResponseType
    {
        public string message;
        public bool isError;
        public bool isValid;
    }

Вывод console.log(result):

<string xmlns="http://tempuri.org/">{ "message": "Документ успешно подписан", "isError": false, "isValid": true }</string>
2
  • Чё-то не то. А вы проверяли, что именно возвращает метод JsonConvert.SerializeObject? Не верится, что он добавляет левые теги.
    – VladD
    23 фев 2015 в 13:08
  • @VladD, выдает { "message": "Документ успешно подписан", "isError": false, "isValid": true } то есть не оборачивет в тег. Думаю, это уже делает ajax-метод, но проблема в том, что если указать ему contentType="application/json" будет 500 ошибка
    – MaboUhha
    24 фев 2015 в 4:32

1 ответ 1

1

Попробуйте использовать не "public string", а "public object", у меня такой проблемы не наблюдалось. Я также использовал $.getJSON, однако если JSON не валидный, как в вашем случае, то "success" не вызовется.

В своём проекте я делал так:

View:

     function getData()
     {
         $.getJSON("/Instruments/GetCandlesticksJson", { secname: cursec + timeInterval, limit: 50 })
                .done(function (jsondata) {
                    createChart(jsondata);
                });
     }

Controller:

[HttpGet]
public object GetCandlesticksJson(string secname, int limit)
{
    if (CurrentUser != null && (!CurrentUser.InRole("Guest") || !CurrentUser.InRole("User")))
        return Repository.GetCandlesticksJson(secname, limit);
    else
    return null;
}

Функция:

public IEnumerable<Candlestick> GetCandlesticks(string secname, int limit)
{
    if (_col == null)
        if (DbCandles.CollectionExists(secname))
            _col = DbCandles.GetCollection(secname);
        else
        {
            DbCandles.CreateCollection(secname);
            _col = DbCandles.GetCollection(secname);
        }
    int offset = (int)_col.Count() - limit;
    return _col.AsQueryable<Candlestick>()
        .Skip(offset >= 0 ? offset : 0)
        .Take(limit);
}

public object GetCandlesticksJson(string secname, int limit)
{
    return JsonConvert.SerializeObject(GetCandlesticks(secname, limit));
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.