C# 应用 - 使用 WepApp 接受 Http 请求
阅读原文时间:2023年07月10日阅读:4

库类:

Owin.dll
    Owin.IAppBuilder

Microsoft.Owin.dll
    Microsoft.Owin.OwinContext

Microsoft.Owin.Hosting.dll
    Microsoft.Owin.Hosting.WebApp

Microsoft.Owin.Host.HttpListener.dll

\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6\System.Net.Http.dll
    System.Net.Http.HttpResponseMessage

System.Web.Http.dll
     System.Web.Http.ApiController、System.Web.Http.HttpConfiguration

System.Web.Http.Owin.dll
System.Net.Http.Formatting.dll

Newtonsoft.Json.dll

1. 代码

1.1 启动

using System;
using System.Web.Http;
using Microsoft.Owin.Hosting;
using Owin;

class HttpServer
{
    static void Main(string[] args)
    {
        string baseAddress = "http://127.0.0.1:8090";

        WebApp.Start<StartUp>(url: baseAddress);

        Console.WriteLine("开始监听", baseAddress);
        Console.ReadKey();
    }
}

internal class StartUp
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var config = new HttpConfiguration();

        // 允许特性路由
        config.MapHttpAttributeRoutes();

        //按控制器controller名称的路由
        var controlroute = config.Routes.MapHttpRoute(
            name: "ControllerApi",
            routeTemplate: "{controller}"
        );

        // web api 接口
        appBuilder.UseWebApi(config);
    }
}

1.2 控制器基类

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;

public class BaseApiController : ApiController
{
    /// <summary>
    /// 创建一个json格式的返回信息,一般用于返回值类型是string(直接返回string如果123,会变成"123"),如果是其它对象类型,直接返回即可,程序会自动转成json
    /// </summary>
    /// <param name="obj">返回信息,如果是字符串,则不进行转换</param>
    /// <param name="encode">返回是的编码</param>
    /// <param name="setting">转换为json时所用的设置</param>
    /// <returns></returns>
    [NonAction()]
    public HttpResponseMessage CreateJsonResponse(object obj, Encoding encode = null, JsonSerializerSettings setting = null)
    {
        // 返回的HttpResponseMessage
        string str;
        HttpStatusCode statusCode;
        HttpResponseMessage result;
        try
        {
            if (obj == null)
            {
                str = null;
                statusCode = HttpStatusCode.NoContent;
            }
            else if (obj is string || obj is char)
            {
                str = obj.ToString();
                statusCode = HttpStatusCode.OK;
            }
            else
            {
                if (setting == null) setting = new JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, DateFormatString = "yyyy-MM-dd HH:mm:ss" };
                str = JsonConvert.SerializeObject(obj, setting);
                statusCode = HttpStatusCode.OK;
            }
            result = new HttpResponseMessage { StatusCode = statusCode, Content = new StringContent(str, encode == null ? Encoding.UTF8 : encode, "application/json") };
        }
        catch (Exception ex)
        {
            result = new HttpResponseMessage { StatusCode = System.Net.HttpStatusCode.InternalServerError, Content = new StringContent(ex.ToString(), encode == null ? Encoding.UTF8 : encode) };
        }
        return result;
    }
}

1.3 业务控制器

/// <summary>
/// Json数据转发控制器
/// </summary>
public class JsonDataForwardController : BaseApiController
{
    #region 接收数据,1.通过put或get并把数据作为参数附在url推送过来,2.通过post并将数据附在body上传送过来。推荐用第2种方法

    /// <summary>
    /// 通过url参数获取接收数据
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    [HttpGet]
    [HttpPut]
    public HttpResponseMessage ReveiveDataFromUrl(string data)
    {
        return CreateJsonResponse(ReveiveData(data));
    }

    /// <summary>
    /// 在body中获取接收数据
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    [HttpPost]
    public HttpResponseMessage ReveiveDataFromBody([FromBody] object data)
    {
        return CreateJsonResponse(ReveiveData(data.ToString()));
    }
    #endregion

    #region 普通请求
    [HttpPost]
    [Route("JsonDataForward/Extend")]
    public HttpResponseMessage ExtendRequest([FromBody] object body)
    {
        return new HttpResponseMessage();
    }
    #endregion

    #region 非http请求方法
    /// <summary>
    /// 处理推送过来的数据
    /// </summary>
    /// <param name="data">推送过来的数据</param>
    /// <returns></returns>
    [NonAction()]
    public string ReveiveData(string data)
    {
        return string.Empty;
    }
}

Post 请求:

  1. http://127.0.0.1:8090/JsonDataForward 触发 ReveiveDataFromBody
  2. http://127.0.0.1:8090/JsonDataForward/Extend 触发 ExtendRequest

3. Http 系列

3.1 发起请求

使用 HttpWebRequest 发起 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501036.html

使用 WebClient 发起 Http 请求 :https://www.cnblogs.com/MichaelLoveSna/p/14501582.html

使用 HttpClient 发起 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501592.html

使用 HttpClient 发起上传文件、下载文件请求:https://www.cnblogs.com/MichaelLoveSna/p/14501603.html

3.2 接受请求

使用 HttpListener 接受 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501628.html

使用 WepApp 接受 Http 请求:https://www.cnblogs.com/MichaelLoveSna/p/14501612.html

使用 WepApp 处理文件上传、下载请求:https://www.cnblogs.com/MichaelLoveSna/p/14501616.html