c# 用控制台创建一个webapi服务需要有HttpResponseMessage返回stream的post接口支持接受客户端传参再演示一下客户端调用例子
首先,我们需要创建一个控制台应用程序并添加必要的NuGet包。
- 创建控制台应用程序
打开Visual Studio并创建一个新的控制台应用程序。
- 添加必要的NuGet包
我们需要添加以下NuGet包:
- Microsoft.AspNet.WebApi.Core
- Microsoft.Owin.Host.HttpListener
可以通过NuGet包管理器或通过控制台窗口使用以下命令安装:
Install-Package Microsoft.AspNet.WebApi.Core
Install-Package Microsoft.Owin.Host.HttpListener
- 创建WebAPI控制器
在项目中添加一个新的类并命名为ValuesController。 确保将其继承自ApiController。
using System.Net.Http;
using System.Web.Http;
namespace WebApiConsoleApp.Controllers
{
public class ValuesController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
var response = new HttpResponseMessage();
var stream = new MemoryStream();
// TODO: 处理客户端传来的参数,并将结果写入stream
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
}
}
}
- 配置WebAPI服务
在Main方法中,我们需要启动WebAPI服务并配置路由。我们可以使用WebApp.Start方法来启动服务。
using Microsoft.Owin.Hosting;
namespace WebApiConsoleApp
{
class Program
{
static void Main(string[] args)
{
const string baseAddress = "http://localhost:9000/";
// 启动WebAPI服务
using (WebApp.Start<Startup>(url: baseAddress))
{
Console.WriteLine("WebAPI服务已启动,按任意键停止...");
Console.ReadKey();
}
}
}
}
- 配置WebAPI路由
在Startup类中,我们需要配置WebAPI路由。 我们可以使用HttpConfiguration类来配置路由。
using System.Web.Http;
namespace WebApiConsoleApp
{
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
- 客户端调用例子
现在我们可以通过以下代码示例来测试我们的WebAPI服务。
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
namespace WebApiConsoleApp.Client
{
class Program
{
static void Main(string[] args)
{
const string baseAddress = "http://localhost:9000/";
// 创建HttpClient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseAddress);
// 创建请求内容
var stream = new MemoryStream();
var writer = new BinaryWriter(stream);
writer.Write("Hello, World!");
writer.Flush();
stream.Position = 0;
var content = new StreamContent(stream);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
// 发送POST请求
var response = client.PostAsync("api/values", content).Result;
response.EnsureSuccessStatusCode();
// 处理响应内容
var resultStream = response.Content.ReadAsStreamAsync().Result;
var reader = new BinaryReader(resultStream);
var result = reader.ReadString();
Console.WriteLine(result);
}
Console.WriteLine("按任意键退出...");
Console.ReadKey();
}
}
}
在上面的代码中,我们创建了一个HttpClient对象并使用PostAsync方法向WebAPI服务发送POST请求,将字符串"Hello, World!"写入到请求流中。 然后,我们从响应流中读取结果,并将其打印到控制台上。
原文地址: http://www.cveoy.top/t/topic/ZMw 著作权归作者所有。请勿转载和采集!