繁体   English   中英

如何在ASP.NET的Web服务中通过HTTP接收数据?

[英]How to receive the data via HTTP in the web service of ASP.NET?

我们的团队正在开发一个应用程序,该应用程序需要通过HTTP协议将数据从Android应用程序发送到ASP.NET服务器,而我负责服务器部分。 我已经决定通过Web服务接收数据,但是我不知道具体的处理方式。 如何在asmx文件中编写Web方法以接收数据?

由于不再真正支持 ASMX 并且您想保持简单,因此编写一个通用处理程序(.ashx)。

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

using System;
using System.Web;
using System.Net;

public class Handler : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {

    //retrieve your data from context.Request. Depending on how you choose to send the data from Android, the data may be in context.Request.QueryString or context.Request.Form or context.Request.Files. Commonly, data is sent back and forth as JSON or XML in the body. See my helper method below for retriving it

    //it's a good idea to let the client know we processed their request successfully
    context.Resonse.StatusCode = HttpStatusCode.OK;
    context.Response.ContentType = "text/plain";
    context.Response.Write("Success"); //this line is redundant because of the status code, but I wanted to show you how to write data to the response
    }

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

如果要从请求正文中获取字符串数据,则此辅助方法应该很方便,可以从here那里借用。

private string GetDocumentContents(HttpRequestBase Request)
{
    string documentContents;
    using (Stream receiveStream = Request.InputStream)
    {
        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
        {
            documentContents = readStream.ReadToEnd();
        }
    }
    return documentContents;
}

如果您想变得更高级,请查看Web APIWCF

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM