簡體   English   中英

如何從Request中獲取Json?

[英]How to get Json from Request?

我使用代碼將一些參數發送到ASP.NET方法:

$.ajax({
        url: "/default.aspx/test.test",
        type: "POST",
        data: "{'parameter':'kapdbe'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            alert(result.d);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Error");
        }
    });

然后,如何獲取從HttpContext.Request發送的數據? 提前致謝。

您需要使用StreamReader Request.InputStream的原始數據讀取為一個字符串,然后從該字符串中解析JSON。

如果使用的是page方法,則可以簡單地修改page方法,以將[Serializable]類作為參數,並具有與傳入JSON匹配的屬性。

你寫了

url: "/default.aspx/test.test"

所以,我猜ASP.NET WebForms對嗎?

將此信息放在問題標簽中總是很好的,因此我們可以幫助您更好更快地

因此,您應該這樣做:

url: "/json/test.ashx"

並創建該通用處理程序 (因此您不需要處理所有的ASP.NET頁面生命周期,它將更快得多)

該代碼將為:

<%@ WebHandler Language="C#" Class="Handler" %>

using System.Web;

public class Handler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        // Get your variable
        string param = context.Request["parameter"];

        // Do something with it    
        MyObject output = DoSomethingWithPAram(param);

        // Use Json.NET to get a nice JSON string
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(output);

        // Output new stuff
        context.Response.ContentType = "text/plain";
        context.Response.Write(json);
    }

    public bool IsReusable {
        get {
            return false;
        }
    }    
}

希望對您有所幫助...如果它是ASP.NET MVC 2/3 ,則稍微容易一些:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM