C# 简单的webapi

最近在看一个C#的项目。之前对C#一点儿不了解 ,谁让我对C++情有独钟。。。

简单流程有必要了解一下,这里写一个基于MVC的简单API项目,支持http post请求并响应。这只是个人入门程序。下面的实例参考另外一个blog的demo,自己又重新实现了一遍https://blog.csdn.net/lwpoor123/article/details/78285148

最后需要测试post 请求,除了CURL,这里推荐安装postman。做接口测试很强大https://www.getpostman.com

  • 新建web项目,支持MVC \webapi,项目结构如下图,.net版本默认4.6的了,其他都是默认,项目结构如下

需要修改的是两个地方,App_Start和Controllers。基本思路是App_Start定义接口,包括路由、参数等,Controllers实现接口。至于他俩怎么连接,目前不清楚。

  • 接口描述(App_Start)

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            // 自定义路由
            config.Routes.MapHttpRoute(
                name: "HelloApi",
                routeTemplate: "api/allo/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                
            );
        }
    }
}

 以上配置定义接口形式为ip:port/api/allo/{controller}/{action}/{id}, id 为参数类型,如果{action}包含参数,这里的参数是必须的,否则无法正确调用接口。

  • 接口实现(Controllers)

namespace WebApplication1.Controllers
{
    public class ApiEmptyController : ApiController
    {
        //private readonly object UserInfo;
        public class UserInfo
        {
            public readonly string USERNAME;

            internal static int GetCount(Func<object, bool> p)
            {
                throw new NotImplementedException();
            }

            internal static int GetCount()
            {
                return 0;
                //throw new NotImplementedException();
            }
        }


        //检查用户名是否已注册
        private ApiTools tool = new ApiTools();
        [HttpPost]
        public HttpResponseMessage CheckUserName(string userName)
        {
            string _userName = "";
            int num = UserInfo.GetCount(/*p => p.USERNAME == _userName*/);//查询是否存在该用户
            if (num > 0)
            {
                return tool.MsgFormat(ResponseCode.操作失败, "不可注册/用户已注册", "1 " + userName);
            }
            else
            {
                return tool.MsgFormat(ResponseCode.成功, "可注册", "0 " + userName);
            }
        }
    }
}
namespace WebApplication1.Controllers
{
    internal class ApiTools
    {
        private string msgModel = "{{\"code\":{0},\"message\":\"{1}\",\"result\":{2}}}";
        public ApiTools()
        {
        }
        public HttpResponseMessage MsgFormat(ResponseCode code, string explanation, string result)
        {
            string r = @"^(\-|\+)?\d+(\.\d+)?$";
            string json = string.Empty;
            if (Regex.IsMatch(result, r) || result.ToLower() == "true" || result.ToLower() == "false" || result == "[]" || result.Contains('{'))
            {
                json = string.Format(msgModel, (int)code, explanation, result);
            }
            else
            {
                if (result.Contains('"'))
                {
                    json = string.Format(msgModel, (int)code, explanation, result);
                }
                else
                {
                    json = string.Format(msgModel, (int)code, explanation, "\"" + result + "\"");
                }
            }
            return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
        }
    }
}
namespace WebApplication1.Controllers
{
    public enum ResponseCode
    {
        操作失败 = 00000,
        成功 = 10200,
    }
    //public class ResponseCode
    //{
    //    internal static ResponseCode 操作失败;
    //    internal static ResponseCode 成功;

    //    public static explicit operator int(ResponseCode v)
    //    {
    //        throw new NotImplementedException();
    //    }
    //}
}
  • 测试

vs编译完成,启动的时候会调用IIS_express 加载服务(大概是这个过程)启动本地浏览器界面。因为我们发的是post请求,所以无法直接从浏览器地址栏返回结果。这里使用postman。

实际测试,如果不定义{action},带上参数也可以调用成功,应该只有一个符合条件的参数可以。

地址栏中的UserInfo 对应路由配置{controller}参数 
           CheckUserName 对应路由配置{action}参数 
           userName=张三 对应 路由配置{id}参数

猜你喜欢

转载自blog.csdn.net/moyebaobei1/article/details/81941481