EpeTuK
@EpeTuK
Full-Stack developer

Как заставить Newtonsoft.Json вернуть чистый json?

Есть сервис на C#, который отдает 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)]
[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>
  • Вопрос задан
  • 2795 просмотров
Решения вопроса 1
AlekseyNemiro
@AlekseyNemiro
full-stack developer
Newtonsoft.Json тут не причем. Дело в запросе, со стороны клиента. Нужно указать тип содержимого application/json и передать JSON в data:
$.ajax({
	type: "POST",
	url: "WebService1.asmx/VerifySignature",
	contentType: "application/json",
	data: JSON.stringify({ certInfo: keyInfo }), // обернуть все параметры
	success: function (result) {
		alert(result);
		console.log(result);
	}
});
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы