首页 > 其他分享 >WebApi-寄宿方式注意事项

WebApi-寄宿方式注意事项

时间:2023-07-26 12:12:39浏览次数:35  
标签:WebApi function string System Id 寄宿 注意事项 using public

所谓的寄宿方式,就是把服务从原来的容器(iis、appache)中提取出来通过宿主程序来控制其启动,这样的好处就是避免了对服务器(容器)的依赖,实现灵活控制,但在实际开发中尤其是新手容易忽略的地方,这里做个简单的示例,记录一下便于以后自查。
  • 首先建立一个公共各类库 Common,用于存放实体类。编写一个实体类 Contact
namespace Common
{
    public class Contact
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string PhoneNo { get; set; }
        public string EmailAddress{get;set;}
        public string Address { get; set; }
    }
}

  • 接着在建立一个类库 SelfHost,用于编写WebApi 控制器(为了让宿主调用,把WebAPI服务放在类库中实现,这和WCF 是一样的)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Common;
using System.Threading;
using Newtonsoft.Json;
using System.Web.Http.Cors;

namespace WebApi
{
    [EnableCors(origins:"*",headers:"*",methods:"*")]  //为了解决跨域问题,这里引用的Cors 要保持和宿主中一致,Newtonsoft.JSon 也是如此
    public class ContactsController:ApiController
    {
        static List<Contact> contacts;
        static int counter = 2;
        public ContactsController()
        {
            contacts = new List<Contact> {
                new Contact{ Id="1001",Name="张三",PhoneNo="13663782541",EmailAddress="[email protected]",Address="河南南阳"},
                new Contact{ Id="1002",Name="李四",PhoneNo="13683782542",EmailAddress="[email protected]",Address="河南信阳"}
            };
        }
        [HttpGet]
        public IEnumerable<Contact> Get(string Id = null) {
            return contacts.Where(c => c.Id == Id||string.IsNullOrEmpty(Id));
        }
        [HttpPost]
        public List<Contact> Post(dynamic obj) {
            Interlocked.Increment(ref counter);
            Contact contact = new Contact {
                Id = counter.ToString("D3"),
                Name = obj.Name,
                PhoneNo=obj.PhoneNo,
                EmailAddress=obj.EmailAddress,
                Address=obj.Address

            };
            contacts.Add(contact);
            return contacts;
        }
        [HttpDelete]
        public List<Contact> Delete(string Id) {
            contacts.Remove(contacts.First(c => c.Id == Id));
            return contacts;
        }

    }
}

  • 最后编写宿主程序,这里以控制台程序为例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Net.Http.Formatting;
using System.Web.Http.SelfHost;
using System.Reflection;
using System.Web.Http.Cors;
namespace SelfHost
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost/selfhost/api/contacts";   // 提供给客户端参考的地址
            Assembly.Load("WebApi,Version=1.0.0.0,Culture=neutral,PublicToken=null");
            HttpSelfHostConfiguration configuration = new   //这里的configuration 和原始WebAPI 的Glob.asxa 中的config 对象是一样的,都是用来为当前的WebApi服务提供配置信息 HttpSelfHostConfiguration("http://localhost/selfhost");  //这里的地址是基地址,即类似原始WebApi中的 localhost:8080
            configuration.Formatters.Remove(configuration.Formatters.XmlFormatter);  //删除默认的xml格式
            configuration.Formatters.Add(new JsonMediaTypeFormatter());   //增加JSON格式 
            configuration.EnableCors(); //启用跨域
            using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration)) {
                httpServer.Configuration.Routes.MapHttpRoute(  //设置服务器的路由信息
                    name:"DefaultApi",
                    routeTemplate:"api/{controller}/{id}",
                    defaults: new { id=RouteParameter.Optional}
                    );
                httpServer.OpenAsync().Wait();  //启动服务
                Console.WriteLine("WebApi 服务器已启动...");
                Console.WriteLine($"地址:{url}");
                Console.Read();
            }
        }
    }
}

  • 启动服务
    image

  • 浏览器访问
    image

  • 测试跨域
    HTHML代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery-1.10.2.js"></script>
		<script>
		
			function f1(){
				$.ajax({
					type:"get",
					url:"http://localhost:58208/api/home",
					data:{},
					async:true,
					success:function(res){
						$("#txt").append(JSON.stringify(res)+"\n");
						
					},
					error:function(err){
						alert(JSON.stringify(err));
					}
					
				});
				
			}
			
           function f2(){
           	$.ajax({
           		type:"get",
           		url:"http://localhost:58208/api/home",
           		data:{"name":"张三"},
           		async:true,
           		success:function(res){
           			$("#txt").append(JSON.stringify(res)+"\n");
           			
           		},
           		error:function(err){
           			alert(JSON.stringify(err));
           			
           		}
           	});

           }
		function f3() {
		
			$.ajax({
				type:"post",
				url:"http://localhost:58208/api/home",
				contentType:"application/json",
				data:JSON.stringify({"name":"张三","age":12}),
				async:true,
				success:function(res){
					$("#txt").append(JSON.stringify(res)+"\n");
				},
				error:function(err){
					alert(JSON.stringify(err));
					
				}
			});
		
			
		}
		function f4(){
			$.ajax({
				type:"get",
				url:"http://localhost/selfhost/api/contacts",
				async:true,
				success:function(res){
					$("#txt").append(JSON.stringify(res));
					
				},
				error:function(err){
					alert(JSON.stringify(err));
					
				}
			});
			
		}
		</script>
	</head>
	<body>
		<div>
			<button onclick="f1()">测试1-Get无参</button>
			<button onclick="f2()">测试2-Get有参</button>
			<button onclick="f3()">测试3-Post动态参数</button>
			<button onclick="f4()">寄宿服务测试-Get</button>
		</div>
		<div>
			<textarea id="txt" rows="25" cols="38" ></textarea>
		</div>
	</body>
</html>

测试效果:
image

标签:WebApi,function,string,System,Id,寄宿,注意事项,using,public
From: https://www.cnblogs.com/sundh1981/p/17582139.html

相关文章

  • .net core WebApi 控制器使用特性校验是否已经登录
    实现 ApiAuthorizeAction自定义类:publicclassApiAuthorizeAction:Attribute,IAuthorizationFilter{publicvoidOnAuthorization(AuthorizationFilterContextcontext){if(context==null)return;......
  • Java 字符串转整形数组的方法及注意事项
     在Java编程中,经常会遇到需要将字符串转换为整形数组的情况。这是一个常见的操作,它可以帮助我们更方便地处理数据。本文将介绍一些常见的方法和注意事项,以帮助您顺利完成字符串转整形数组的任务。方法一:使用split()方法split()方法是Java中常用的字符串分割方法,它可以按照指......
  • 一点注意事项(实时更新)
    一点注意事项(实时更新)函数没事干不要封装着玩,会T的很惨。不要对STL的速度抱有侥幸且不合理的幻想。如果可以,尽量不用string。请不要对自己的口胡能力过度自信,认真计算复杂度。不要偷懒,过度依赖平板电视等外部库的模板不利于青少年智力发展。如果需要使用指针,请关注时空复杂......
  • .net webapi导出excel
    publicIActionResultdownloadWeeklyTemplate(){stringbasePath=AppDomain.CurrentDomain.BaseDirectory;stringpath=basePath+"/excel.xlsx";varf=newFileInfo(path);if(!f.Exists......
  • WebApi 动态参数 dynamic 使用
    在调用WebAPI时,调用方法主要有get和post,但参数传递需要注意几点,下面简单介绍一下ajax调用时传参的几种方法:webapiusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;usingSystem.Web.Http;usingSystem.Web.......
  • 使用参数属性对.Net WebApi参数校验
    .NetWebApi进行优雅的参数校验受到了springboot中注解校验参数的启发,于是想,难道微(巨)软(硬)的.net不行吗?于是有了本次尝试。当我们日常开发webapi接口时,难免会有一堆参数校验,例如校验参数是否为空,密码长度……条件校验一般的操作是下面这样的:emm……目前这是2个字段参......
  • with torch.no_grad():注意事项
    1。当执行原地操作时,例如tensor.add_(x),将会在一个张量上直接修改数据,而不会创建新的张量。由于修改了张量的数据,因此计算图会失效,即计算图中的操作和输入输出关系都会发生变化。这会导致反向传播无法正确计算梯度。因此,PyTorch禁止在需要梯度计算的张量上执行原地操作。为了解......
  • .net core webapi 局域网内机器可以互相访问
    1、  使用localhost的方式运行程序  dotnetFitnessequipment.dll--urls=http://localhost:5038    是无法通过ip访问的,只可以使用localhost访问    2、以ip方式运行程序,dotnetFitnessequipment.dll--urls=http://192.168.3.213:5038     ......
  • 在调试状态下使用本机ip访问webapi
    1、在调试模式下无法通过ip访问webapi,但是可以使用localhost或者127.0.0.1加端口访问   2、因为在调试模式下运行它,Vs2022默认正在使用IIS-Express。默认情况下,IIS-Express仅绑定到localhost. 3、为了调试状态可以通过ip访问,需要打开位于以下位置的IIS-Express应用......
  • Codility / LeetCode的重要性与注意事项
    Codility/Leetcode不只会针对回答内容给出最终分数,也会一并记录解题的过程供面试官参考;相较于现场考试,Codility/Leetcode可以省下更多时间,也能让求职者在最熟悉的环境发挥实力。 进行测验前先查看Codility/LeetcodeFAQ,并完成demo题。可试着多做几题练习题,能全部做......