.NET Core Web API

.NET 实现

.NET Core:完全实现.NET Standard,可在Windows、macOS和Linux运行

.NET Framework:4.5以上实现.NET Standard,仅Windows。很多独有的框架,如WPF。

Mono:用于Android和所有Apple系统,驱动Xamarin和Unity

UWP:统一微软各类设备(Windows、Xbox、Windows Phone等)

https和http协议

Web API Post实例:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI_Core.Models;

namespace WebAPI_Core.Controllers
{
    [Route("api/[controller]")]  //路由
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private static Dictionary DB = new Dictionary();

        // POST api/
        [HttpPost]
        public AddResponse Post([FromBody] AddRequest req)
        {
            AddResponse resp = new AddResponse();
            try
            {
                DB.Add(req.ISBN,req);
                resp.ISBN = req.ISBN;
                resp.message = "交易成功";
                resp.result = "success";


            }catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
                resp.ISBN = "";
                resp.message = "交易失败";
                resp.result = "fail";
            }

            return resp;
        }

        /* AddRequest
        {
        	"ISBN": "1",
        	"name": "1",
        	"price": 1,
        	"date": "20200219 ",
        	"authors": [{
        			"name": "jerry",
        			"sex": "M",
        			"birthday": "19990909"
        		},
        		{
        			"name": "tom",
        			"sex": "M",
        			"birthday": "19980808"
        		}
        	]
        }
        */
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI_Core.Models
{
    public class AddRequest
    {
        //创建数据结构
        public string ISBN;
        public string name;
        public decimal price;
        public string date;
        public object[] authors;
    }
    public class Author
    {
        public string name;
        public string sex;
        public string birthday;
    }

    public class AddResponse
    {
        public string result;
        public string message;
        public string ISBN;
    }
}

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI_Core
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI_Core", Version = "v1" });
            });

            // .net core Json设置后台确定大小写
            services.AddControllers()
            .AddNewtonsoftJson(options =>
            
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI_Core v1"));
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

调用API

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NetCore_MVC2.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Text;
using System.IO;

namespace NetCore_MVC2.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger _logger;

        public HomeController(ILogger logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            string url = "https://localhost:44375/api/Values";
            AddRequest req = new AddRequest();
            req.ISBN = "1";
            req.name = ".Net Core";
            req.authors = null;
            req.price = 1m;  //decimal

            //对象转json
            string postData = Newtonsoft.Json.JsonConvert.SerializeObject(req);

            string result = Post(url, postData, "application/json");

            ViewData["result"] = result;
            return View();


            //使用C#做HTTP post
        }

        //https://www.cnblogs.com/zhang1f/p/11469650.html
        /// 
        /// 
        /// 
        /// 
        /// 
        /// application/json
        /// 
        public static string Post(string url, string postData, string contentType)
        {

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = contentType;
                request.Method = "POST";
                request.Timeout = 100000;

                byte[] bytes = Encoding.UTF8.GetBytes(postData);
                request.ContentLength = bytes.Length;
                using (Stream writer = request.GetRequestStream())
                {
                    writer.Write(bytes, 0, bytes.Length);
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8))
                    {
                        string result = reader.ReadToEnd();
                        return result;
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }


        }


        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

你可能感兴趣的:(ASP.NET,.netcore)