[Getting Started 1] C# webApi creation, publishing, deployment, and api calling

1. Building web api item

1.1. Project creation

MVC architecture will have three layers: view-model-control. In the web api, its front-end and back-end are separated. , so there are only two layers of model-control in the project

1.2. Modify routing

Open the App_Start folder, WebApiConfig.cs,Modify the route and add {action}/, so that we can use the interface function name in the api interface to direct what we want The api function to be called, otherwise, it can only be directed through the controller, which may cause conflicts between functions with different names with the same parameters. Among them, {id} is the parameter in the API interface function.
 

The default routing configuration information is: [The default routing template cannot satisfy multiple operations for one resource and one request method. 】
The default route of WebApi is to match the corresponding action through the http method (get/post/put/delete), which means that the default route of WebApi does not need to specify the name of the action

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

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

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

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                //修改路由,加上{action}/ ,这样就可以在api接口中通过接口函数名,来导向我们希望调用的api函数,
                //否则,只能通过controller来导向,就可能会造成有相同参数的不同名函数,冲突。其中,{id}是api接口函数中的参数
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

2. Test cases

Write a test api function and start execution (without debugging)

2.1. We add a class movie in the model folder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAPI.Models
{
    public class movie
    {

        public string name { get; set; }
        public string director { get; set; }
        public string actor { get; set; }
        public string type { get; set; }
        public int price { get; set; }



    }
}

2.1.2. We add a class Product in the model folder

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAPI.Models
{
    public class Product
    {

        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }



    }
}

2.2. Add the web api controller under the controller folder and change the name to TestController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class TestController : ApiController
    {


        movie[] mymovie = new movie[]
        {
            new movie { name="海蒂和爷爷",director="阿兰.葛斯彭纳",actor="阿努克",type="动漫",price=28},
            new movie { name="云南虫谷",director="佚名",actor="潘粤明",type="惊悚",price=32},
            new movie { name="沙海",director="佚名",actor="吴磊",type="惊悚",price=28},
            new movie { name="千与千寻",director="宫崎骏",actor="千寻",type="动漫",price=28}
        };
        public IEnumerable<movie> GetAllMovies()
        {
            return mymovie;

        }
        public IHttpActionResult GetMovie(string name)    //异步方式创建有什么作用
        {
            var mov = mymovie.FirstOrDefault((p) => p.name == name);
            if (mymovie == null)
            {
                return NotFound();
            }
            return Ok(mymovie);
        }





    }
}

This completes the writing of a web api instance

2.2.2. Add the web api controller under the controller folder and change the name to productsController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class productsController : ApiController
    {

        Product[] products = new Product[]
        {
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }




    }
}

2.2.3. Add the web api controller under the controller folder and change the name to MyController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebAPI.Controllers
{
    public class MyController : ApiController
    {


        [HttpGet]
        public string MyExample(string param1, int param2)
        {
            string res = "";
            res = param1 + param2.ToString();
            //这边可以进行任意操作,比如数据存入或者取出数据库等
            return res;
        }




    }
}

3. Local debugging

3.1 Run debugging and access as localhost (or 127.0.0.1)
①Click the toolbar [IIS Express]

② Browse the address input interface to see if it can be accessed

localhost:44381/api/products/GetAllProducts

Notice:

The path here is to write the prefix name of your controller (the prefix of the productsController controller file under the Control file)

https://localhost:44381/api/Test/GetAllMovies

2) You can also debug directly in the browser

If you want to debug the value, you can modify the code of WebApiConfig.cs as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

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

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

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                //修改路由,加上{action}/ ,这样就可以在api接口中通过接口函数名,来导向我们希望调用的api函数,
                //否则,只能通过controller来导向,就可能会造成有相同参数的不同名函数,冲突。其中,{id}是api接口函数中的参数
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


            //去掉xml返回格式、设置json字段命名采用
            var appXmlType =
                config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);





        }
    }
}

ok, shows success

localhost:44381/api/My/MyExample?param1=&param2=2

WebApi project example 3-1

3-1 (1) Newly added to the controller UserInfoController,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class UserInfoController : ApiController
    {

        //检查用户名是否已注册
        private ApiTools tool = new ApiTools();

        //  [HttpPost]

        [HttpGet]
        public HttpResponseMessage CheckUserName(string _userName)
        {
            int num = UserInfoGetCount(_userName);//查询是否存在该用户
            if (num > 0)
            {
                return tool.MsgFormat(ResponseCode.操作失败, "不可注册/用户已注册", "1 " + _userName);
            }
            else
            {
                return tool.MsgFormat(ResponseCode.成功, "可注册", "0 " + _userName);
            }
        }

        private int UserInfoGetCount(string username)
        {
            //return Convert.ToInt32(SearchValue("select count(id) from userinfo where username='" + username + "'"));
            return username == "admin" ? 1 : 0;
        }





    }
}

Add return (response) class ApiTools

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;

namespace WebAPI.Models
{
    //添加返回(响应)类
    public 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") };
        }
    }


    public enum ResponseCode
    {
        操作失败 = 00000,
        成功 = 10200,
    }



}

3-1 (2) Local debugging, calling Web API interface

Run debugging and access as localhost (or 127.0.0.1)
①Click the toolbar [IIS Express]

② Browse the address input interface to see if it can be accessed

https://localhost:44381/api/UserInfo/CheckUserName?_userName=wxd

3.2 Run debugging and access in the form of local IP (192.168.6.152)
127.0.0.1 is the loop address to test the local TCP/IP protocol stack and serve during actual use The terminal is not on this machine, but an external address. You need to use the IP address for testing.
External users use IP + port number to access. As shown in the figure below, the browser cannot access and gets a 400 error.
 

solution:

Because IIS 7 adopts a more secure web.config management mechanism, configuration items are locked by default and do not allow changes.

Run the command line as administrator[Do not operate here]

C:\windows\system32\inetsrv\appcmd unlock config -section:system.webServer/handlers

If modules are also locked, run again

C:\windows\system32\inetsrv\appcmd unlock config -section:system.webServer/modules

Client program: The calling interface is divided into the following situations:
Calling Web API through Javascript and jQuery
Right-click the resource manager solution below project, add-new item

Replace index.html content with:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Product App</title>
</head>
<body>

    <div>
        <h2>All Products</h2>
        <ul id="products" />
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="prodId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="product" />
    </div>

    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script>
    var uri = 'api/Products';

    $(document).ready(function () {
      // Send an AJAX request
      $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
              // Add a list item for the product.
              $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
          });
    });

    function formatItem(item) {
      return item.Name + ': $' + item.Price;
    }

    function find() {
      var id = $('#prodId').val();
      $.getJSON(uri + '/' + id)
          .done(function (data) {
            $('#product').text(formatItem(data));
          })
          .fail(function (jqXHR, textStatus, err) {
            $('#product').text('Error: ' + err);
          });
    }
    </script>
</body>
</html>

4. Publish web api and deploy

4.1. First, right-click the project and select Publish:

At this point, the program has been published to the specified path (the path here can be a folder on the local machine or an ftp path on the server)

4.2. We have the last step left, which is to hang up the published server program on IIS. No more details, just the picture above:
Open iis and select the website. , right-click to add a website, 

 OK, the server program is released and deployed.

This WebAPI is what we just deployed. Click Browse *91 (http) on the right side of the picture below to open the web page.

Guess you like

Origin blog.csdn.net/zgscwxd/article/details/133823295