【问题标题】:Handle POSTs differently than GET以不同于 GET 的方式处理 POST
【发布时间】:2014-01-02 04:11:26
【问题描述】:

我目前在我的 C# 处理程序 (.ashx) 中使用 context.Request.QueryString,因为到目前为止我只需要处理 GET 帖子。

如果我通过 POST 方法发送一个 JSON 对象怎么办?我知道我应该反序列化发送的内容,但我的意思是 - 我怎么知道发送源发送的是 POST 还是 GET。

为什么?因为我想将处理程序拆分为与 POST 相关的功能(通常需要安全的东西)和更原始的 GET 相关功能(检索公共信息等)

如果重要的话,我的代码现在看起来像这样(它还没有准备好正确处理 POST)。

public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "application/json";
    JavaScriptSerializer jss = new JavaScriptSerializer();

    // Wanna know POST was used here, so I can deserialize the sent JSON data
    // ----

    // Handling GET here, good and working
    if (context.Request.QueryString["aname"] != null
        && context.Request.QueryString["type"] != null)
    {
         string adminName = context.Request.QueryString["aname"];
         if(adminName == "test") { // Return some JSON object }
    }
}

【问题讨论】:

    标签: c# asp.net json post handler


    【解决方案1】:

    您可以访问context.Request,因此您可以简单地使用它的HttpMethod property 来确定它是POST、GET 还是其他方式。

    【讨论】:

      【解决方案2】:

      您可以使用Request.Form[parameter] 进行POST。查看相关帖子:How to handle C# .NET GET / POST?

      要检查请求是 POST 还是 GET,可以使用 HttpContext.Current.Request.HttpMethod(来自 Detect if action is a POST or GET method)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-02
        • 1970-01-01
        • 2023-02-25
        • 2014-03-29
        • 2020-07-28
        相关资源
        最近更新 更多