【问题标题】:How to use "Fetch API" to pass data between javascript and c#?如何使用“Fetch API”在 javascript 和 c# 之间传递数据?
【发布时间】:2018-09-10 15:55:55
【问题描述】:

我知道如何通过ajax在javascript和c#之间传递数据,现在我想知道fetch。

c#:

namespace WebApplication1
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    //[System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

javascript:

fetch('http://localhost:62177/WebService1.asmx/HelloWorld')
    .then(response => {
        alert(response.json());
    })
    .then(response => {
        alert(response);
    })

它显示:

这个url的使用是基于ajax的。

我把网址改成“http://localhost:62177/WebService1.asmx?op=HelloWorld”,它显示:

我以为是响应成功,但是我什么也没收到,它显示:

然后我修改了返回数据的方法,现在是json-format:

c#:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public void HelloWorld()
{
    object JSONObj = JsonConvert.SerializeObject("Hello World");
    Context.Response.Write(JSONObj);
}

但没有任何变化。

我不知道如何改变它。有人可以帮我一点忙吗?

【问题讨论】:

  • 看起来你根本没有将服务器设置为发送 JSON - 所以你当然会在尝试解析 JSON 时遇到错误
  • how to pass data between javascript and c# by ajax ...您的“ajax”代码使用 JSON 吗?我的意思是,你说你知道的ajax 方法中的服务器端代码无论如何都是一样的,对吧。那么,您的“ajax”方法是否使用 JSON.parse?
  • System.Web.Services.WebService 的页面声明“[d] 定义了 XML Web 服务的可选基类”。 XML 不是 JSON。使用开发人员工具中的网络选项卡查看原始响应并查看返回的内容。

标签: javascript c# json http fetch-api


【解决方案1】:

您的 Web 服务的输出不会生成 JSON。它应该输出 "Hello World" 时应该说如下内容:

{"YourKeyHere":"Hello World"}

我会将网络服务代码更改为如下内容:

    [WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat System.Web.Script.Services.ResponseFormat.Json)]
    public void HelloWorld()
    {
        var obj = new { YourKeyHere = "Hello World" };
        string JSONObj = JsonConvert.SerializeObject(obj);
        Context.Response.Write(JSONObj);
    }

在您的 Web 服务顶部,取消注释此装饰:[System.Web.Script.Services.ScriptService]。它需要取消注释,以便 JavaScript(可能还有其他客户端)可以看到您的服务。

在您的 JavaScript 中,您的响应将以文本(而不是 json)形式返回,并且会附带一个 {"d":null} 括号。为了清理它,我使用了子字符串并将它们放在不同的函数中:

    function SayHello()
    {
    //...
    var options = {
            method: 'GET' ,                              
            headers: {
                'Content-Type': 'application/json',
            }
        };
        fetch("http://localhost:62177/WebService1.asmx/HelloWorld", options)
            // Handle success
            .then(response => response.text())               
            .then(result => DisplayResponse(result))
            .catch(err => console.log('Request Failed', err));
    //...
    }

    function DisplayResponse(result) {                   
        console.log(result); //not sure why 'd:null' shows in output
        console.log(result.substring(0, result.indexOf('{"d":null}'))); //get rid of 'd:null'
        console.log(JSON.parse(result.substring(0, result.indexOf('{"d":null}')))); //get rid of 'd:null' then parse

    }

【讨论】:

    【解决方案2】:

    您首先需要确保您的服务器返回的是 JSON 格式的内容。但是另外,在你的 JS 中,你必须 return response.json()(或 response.text() or whatever method is appropriate) infetch` 以便处理流,以便在下一个函数中得到响应:

    fetch('http://localhost:62177/WebService1.asmx/HelloWorld')
      .then(response => {
        return response.json();
      })
      .then(responseJSON => {
        alert(responseJSON);
      })
    

    初始响应是一个响应流对象,实际上还没有包含任何数据。

    【讨论】:

    • 错误提示服务器没有响应 JSON
    • object JSONObj = JsonConvert.SerializeObject("Hello World"); Context.Response.Write(JSONObj);这是服务端的返回方式,是json格式的。但是,它仍然会出错。
    猜你喜欢
    • 1970-01-01
    • 2015-04-01
    • 2019-09-11
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多