WebApi series summarizes knowledge

WebApi Knowledge Series

A, webApi project to build
1, the new project WebApi

(1)

(2)

(3)

(4)

Areas – HelpPage – App_Start – HelpPageConfig.cs

View Project Properties, copy the xml address

anti Notes - change the path, using the addresses on the map xml acquired:

(5)

App_Start - RouteConfig.cs

Add code

routes.MapRoute(
    "HelpPage", // 路由名称
    "{controller}/{action}/{id}", // 带有参数的 URL
    new { controller = "help", action = "Index", id = UrlParameter.Optional }, // 参数默认值
    new string[] { "mvcProject.Areas.HelpPage.Controllers" }
).DataTokens.Add("Area", "HelpPage");


App_Start - WebApiConfig.cs

Add {action}

After the addition FIG controller:

(6)

Run effect diagram:


2, cross-domain issues

Web.config

Add code

1  <add key="cors_allowOrigins" value="*" />  
2  <add key="cors_allowHeaders" value="*" />  
3  <add key="cors_allowMethods" value="*" />  

cors_allowOrigins representation allows the site requested request * indicates Allow all sites

App_Start – WebApiConfig.cs

Add code:

using System.Configuration;  
var allowOrigins = ConfigurationManager.AppSettings["cors_allowOrigins"]; 
var allowHeaders = ConfigurationManager.AppSettings["cors_allowHeaders"];    
var allowMethods = ConfigurationManager.AppSettings["cors_allowMethods"];  
var globalCors = new System.Web.Http.Cors.EnableCorsAttribute(allowOrigins, allowHeaders, allowMethods)
{ 
    SupportsCredentials = true
};  
config.EnableCors(globalCors); 

After the addition as shown:

Tips System.Web.Http absent "Cors" If added, the solution as follows

Source:

Link: https: //pan.baidu.com/s/1sw7u2I35-G3xLjfzzk2jFQ
extraction code: rd55
or micro-channel two-dimensional code:

Appendix: webapi configuration using System.Web.Http.Cors few notes cross-domain access (Transfer from: https: //blog.csdn.net/chaoyangzhixue/article/details/52251322)

System.Web.Http.Cors配置跨域访问的两种方式
使用System.Web.Http.Cors配置跨域访问,众多大神已经发布了很多文章,我就不在详细描述了,作为小白我只说一下自己的使用心得。在webapi中使用System.Web.Http.Cors配置跨域信息可以有两种方式。 
  一种是在App_Start.WebApiConfig.cs的Register中配置如下代码,这种方式将在所有的webapi Controller里面起作用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

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

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

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //这是重点,从配置文件的appsettings节点中读取跨域的地址
            var cors = new EnableCorsAttribute(ConfigurationManager.AppSettings["origins"], "*", "*");
            config.EnableCors(cors);
        }
    }
}
配置文件如下,注意一定要加上http
<add key="origins" value="http://localhost:9012,http://192.168.1.108:9012" />
第二种方式就是在每个webapiController类中设置,即每个控制器个性化配置,如下代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Cors;
using System.Web.Mvc;

namespace Service.Controllers
{
    [EnableCors("http://localhost:9012,http://192.168.1.108:9012", "*", "*")]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
    }
}

注意事项
EnableCors共三个参数分别为origins、headers和methods。origins配置允许访问的域名,多个域名以逗号分隔即可,域名一定要完整,如果是ip地址前面要加上“http”,只使用IP的话一定会失效的。参数headers配置所支持的资源。参数methods配置支持的方法,get、post、put等。如果允许任意域名、任意资源、任意方法访问自己的webapi,则三个参数全部使用星号”*”即可。
“EnableCors(“http://localhost:9012,http://192.168.1.108:9012“, ““, ““)”中的配置如果出现错误的话不会报错,而是直接禁止未出现在配置表中的资源访问。
如果使用第一种方式那么可以从配置文件中读取网站列表,如果使用第二种方式,所有的参数只能使用常量。
3, the request mode

http://www.cnblogs.com/landeanfen/p/5337072.html

WebApi interface test tools: WebApiTestClient

Reference: https: //www.cnblogs.com/landeanfen/p/5210356.html

(1) New webApi Project: WebApiTestClient

(2) Use NuGet installation WebApiTestClient plug

after the introduction of successful project which will add some key documents:

Scripts\WebApiTestClient.js
Areas\HelpPage\TestClient.css
Areas\HelpPage\Views\Help\DisplayTemplates\TestClientDialogs.cshtml
Areas\HelpPage\Views\Help\DisplayTemplates\TestClientReferences.cshtml

(3) modify Api.cshtml file
through the above steps, the assembly can come WebAPITestClient introduced. : Now we only need to do one thing: open the file (according Areas \ HelpPage \ Views \ Help) Api.cshtml and add the following
@ Html.DisplayForModel ( "TestClientDialogs")
@ Html.DisplayForModel ( "TestClientReferences")
after adding Api Code .cshtml file is as follows:

@using System.Web.Http
@using WebApiTestClient.Areas.HelpPage.Models
@model HelpPageApiModel
@{
    var description = Model.ApiDescription;
    ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath;
}
<link type="text/css" href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
<div id="body" class="help-page">
    <section class="featured">
        <div class="content-wrapper">
            <p>
                @Html.ActionLink("Help Page Home", "Index")
            </p>
        </div>
    </section>
    <section class="content-wrapper main-content clear-fix">
        @Html.DisplayForModel()
    </section>
</div>
@Html.DisplayForModel("TestClientDialogs")
@section Scripts{
    <link href="~/Areas/HelpPage/HelpPage.css" rel="stylesheet" />
    @Html.DisplayForModel("TestClientReferences")
}

(4) configured to read comments xml path
real, through the above steps, we can project has been up and running, you can also call interface testing. However, it can not be read ///

Notes inside. The job needs to be done as follows.
As follows: Item Properties

read path in xml: HelpPageConfig.cs inside the lower arrangement of FIG word, the read path specified xml

code is as follows:config.SetDocumentationProvider( new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/bin/WebApiTestClient.xml")));//配置 读取注销的xml路径

(5) add a controller: TestChargingDataController

  /// <summary>
    /// 测试API Test Client 
    /// </summary> 
    public class TestChargingDataController : ApiController 
    {
        /// <summary>
        /// 得到所有数据
        /// </summary>
        /// <returns>返回数据</returns>  
        [HttpGet]
        public string GetAllChargingData()
        { 
            return "ChargingData";
        }
        /// <summary> 
        /// 得到当前Id的所有数据
        /// </summary>
        /// <param name="id">参数Id</param>
        /// <returns>返回数据</returns>
        [HttpGet]
        public string GetAllChargingData(string id)
        {
            return "ChargingData" + id ;
        }
        /// <summary>
        /// Post提交
        /// </summary>
        /// <param name="oData">对象</param>
        /// <returns>提交是否成功</returns>
        [HttpPost]
        public bool Post(TB_CHARGING oData)
        {
            return true;
        }
        /// <summary>
        /// Put请求
        /// </summary>
        /// <param name="oData">对象</param>
        /// <returns>提交是否成功</returns>
        [HttpPut]
        public bool Put(TB_CHARGING oData)
        {
            return true;
        }
        /// <summary>
        /// delete操作
        /// </summary>
        /// <param name="id">对象id</param>
        /// <returns>操作是否成功</returns>
        [HttpDelete]
        public bool Delete(string id)
        {
            return true;
        }
    }
    /// <summary>
    /// 充电对象实体
    /// </summary>
    public class TB_CHARGING
    {
        /// <summary>
        /// 主键Id
        /// </summary>
        public string ID { get; set; }
        /// <summary>
        /// 充电设备名称
        /// </summary>
        public string NAME { get; set; }
        /// <summary>
        /// 充电设备描述
        /// </summary>
        public string DES { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CREATETIME { get; set; }
    } 

Run the project: http: // localhost: 8080 / Help / Index or http: // localhost: 8080 / Help
renderings:

https://blog.csdn.net/qq_22267353/article/details/82216535

4, packaged and released


Add a site:


5,80 port
  1. If port 80 is not occupied
    browsing the web service default port number is 80, for example http://www.abc.com and http://www.abc.com:80 access result is the same, so long as the input URL, do not enter ": 80."
    As shown below:

  2. If port 80 is occupied (this one from the Internet to look not understand ???)
    If port 80 is already in use, can not be modified to port 80, you need to write from the service port 80 of a Web page jump to oa:
    website as follows:

    For example: oa build a directory under the application www.abc.com, and then create a page index.html, the code is as follows:
<script>
location.href="http://www.abc.com:8080/oa";
</script>

Guess you like

Origin www.cnblogs.com/newcapecjmc/p/11734714.html