當前位置:首頁 » 網頁前端 » webapi教程
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

webapi教程

發布時間: 2022-02-08 06:03:31

❶ webApi如何將一個頁面

第一步:新建項目後,找到Global.asax文件----找到GlobalConfiguration.Configure(WebApiConfig.Register)方法------按F12進入 WebApiConfig.Register方法中----添加內容紅框框

知識點:路由器注冊順序是由上往下的,會先從上面進行匹配。

路由器的名稱不能重名,否則報錯【CustomApi/DefaultApi】

第二步:設置webapi項目為啟動項,然後啟動,在網頁路徑上加api/values(控制器名稱不要Controller)

知識點:因為ValuesController是項目自帶的,那麼這一次的請求與 DefaultApi的路由規格是一致的。

❷ winform 怎麼新建webapi

個人建議WCF和WebAPI都要學,WebAPI僅限http協議,如果要追求高性能而使用tcp協議那就得上WCF,一個功能全面、API多樣,一個輕巧,如果只是用於ajax後端那肯定是WebAPI了,如果是用於更復雜多變的環境還是WCF強。

❸ 如何在用C#製作的網站上調用web api和web service。我是新手,希望能有詳細的介紹,或者提供教程。

你的api沒見過,不好說怎麼調用,但是即使是沒有ws和api,只要那個總站上的數據在它的頁面上有顯示,理論上就可以以將數據採集回來的,原理很簡單,就是通過你的程序去獲取網頁代碼,然後在代碼中分析提取你需要的數據,網路一下c# 網站採集,可以找到很多示例。

❹ c# ASP.net mvc web API 學web api 到底學的是什麼我現在知道get,

mvc4 的webapi 不好用,它規定的參數,格式太死了,我感覺,本來我也想用的
什麼從url就能看出是什麼操作,我覺得不是很方便
後來用wcf

❺ 求Web API教程方面的視頻資料!

說真的,可以去傳智官網看。有關IT行業的或者是他們有的學科,有很多免費的資料的。視頻筆記源碼全部都有。

❻ 如何使 WebAPI 自動生成漂亮又實用在線API文檔

1.1 SwaggerUI

SwaggerUI 是一個簡單的Restful API 測試和文檔工具。簡單、漂亮、易用(官方demo)。通過讀取JSON 配置顯示API. 項目本身僅僅也只依賴一些 html,css.js靜態文件. 你可以幾乎放在任何Web容器上使用。

1.2 Swashbuckle

Swashbuckle 是.NET類庫,可以將WebAPI所有開放的控制器方法生成對應SwaggerUI的JSON配置。再通過SwaggerUI 顯示出來。類庫中已經包含SwaggerUI 。所以不需要額外安裝。

2.快速開始

創建項目 OnlineAPI來封裝網路音樂服務(示例下載) ,通過API可以搜索、獲取音樂的信息和播放連接。

我盡量刪除一些我們demo中不會用到的一些文件,使其看上去比較簡潔。

WebAPI 安裝 Swashbuckle

Install-Package Swashbuckle

代碼注釋生成文檔說明。
Swashbuckle 是通過生成的XML文件來讀取注釋的,生成 SwaggerUI,JSON 配置中的說明的。
安裝時會在項目目錄 App_Start 文件夾下生成一個 SwaggerConfig.cs 配置文件,用於配置 SwaggerUI 相關展示行為的。如圖:

將配置文件大概99行注釋去掉並修改為
c.IncludeXmlComments(GetXmlCommentsPath(thisAssembly.GetName().Name));

並在當前類中添加一個方法

/// <summary>
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
protected static string GetXmlCommentsPath(string name)
{
return string.Format(@"{0}\bin\{1}.XML", AppDomain.CurrentDomain.BaseDirectory, name);
}

緊接著你在此Web項目屬性生成選卡中勾選 「XML 文檔文件」,編譯過程中生成類庫的注釋文件

添加網路音樂 3個API

訪問 http://<youhost>/swagger/ui/index,最終顯示效果

我們通過API 測試API 是否成功運行

3.添加自定義HTTP Header

在開發移動端 API時常常需要驗證許可權,驗證參數放在Http請求頭中是再好不過了。WebAPI配合過濾器驗證許可權即可

首先我們需要創建一個 IOperationFilter 介面的類。IOperationFilter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.Filters;
using Swashbuckle.Swagger;

namespace OnlineAPI.Utility
{
public class HttpHeaderFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry
schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null) operation.parameters = new
List<Parameter>();
var filterPipeline =
apiDescription.ActionDescriptor.GetFilterPipeline();
//判斷是否添加許可權過濾器
var isAuthorized = filterPipeline.Select(filterInfo =>
filterInfo.Instance).Any(filter => filter is IAuthorizationFilter);
//判斷是否允許匿名方法
var allowAnonymous =
apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();

if (isAuthorized && !allowAnonymous)
{
operation.parameters.Add(new Parameter
{
name = "access-key",
@in = "header",
description = "用戶訪問Key",
required = false,
type = "string"
});
}
}
}
}

在 SwaggerConfig.cs 的 EnableSwagger 配置匿名方法類添加一行注冊代碼
c.OperationFilter<HttpHeaderFilter>();

添加Web許可權過濾器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Newtonsoft.Json;

namespace OnlineAPI.Utility
{
/// <summary>
///
/// </summary>
public class AccessKeyAttribute : AuthorizeAttribute
{
/// <summary>
/// 許可權驗證
/// </summary>
/// <param name="actionContext"></param>
/// <returns></returns>
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var request = actionContext.Request;
if (request.Headers.Contains("access-key"))
{
var accessKey = request.Headers.GetValues("access-key").SingleOrDefault();
//TODO 驗證Key
return accessKey == "123456789";
}
return false;
}

/// <summary>
/// 處理未授權的請求
/// </summary>
/// <param name="actionContext"></param>
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
var content = JsonConvert.SerializeObject(new {State = HttpStatusCode.Unauthorized});
actionContext.Response = new HttpResponseMessage
{
Content = new StringContent(content, Encoding.UTF8, "application/json"),
StatusCode = HttpStatusCode.Unauthorized
};
}
}
}

在你想要的ApiController 或者是 Action 添加過濾器
[AccessKey]

最終顯示效果

4.顯示上傳文件參數

SwaggerUI 有上傳文件的功能和添加自定義HTTP Header 做法類似,只是我們通過特殊的設置來標示API具有上傳文件的功能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Description;
using Swashbuckle.Swagger;

namespace OnlineAPI.Utility
{
/// <summary>
///
/// </summary>
public class UploadFilter : IOperationFilter
{

/// <summary>
/// 文件上傳
/// </summary>
/// <param name="operation"></param>
/// <param name="schemaRegistry"></param>
/// <param name="apiDescription"></param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (!string.IsNullOrWhiteSpace(operation.summary) && operation.summary.Contains("upload"))
{
operation.consumes.Add("application/form-data");
operation.parameters.Add(new Parameter
{
name = "file",
@in = "formData",
required = true,
type = "file"
});
}
}
}
}

在 SwaggerConfig.cs 的 EnableSwagger 配置匿名方法類添加一行注冊代碼
c.OperationFilter<UploadFilter>();

API 文檔展示效果

❼ WebAPI下的如何實現參數綁定

WebAPI下的如何實現參數綁定

本文將概述在WebAPI方式下將如何將參數綁定到一個action方法,包括參數是如何被讀取,一系列規則決定特定環境採用的那種綁定方式,文章最後將給出一些實際的例子。
Parameter binding說到底是接到一個Http請求,將其轉換成.NET類型使得action方法的簽名更易於理解。
請求消息(request message)包括了請求的所有信息,如帶查詢字元串的請求地址(URL),內容主體(content body)及頭部信息(header)。在沒有採用parameter binding
的情況下,每個action方法將需要接收request message,並手動從中提取出參數,如下所示:
public object MyAction(HttpRequestMessage request){ // make explicit calls to get parameters from the request object int id = int.Parse(request.RequestUri.ParseQueryString().Get("id")); // need error logic! Customer c = request.Content.ReadAsAsync().Result; // should be async! // Now use id and customer}
很顯然,這樣的方式醜陋,易出錯,代碼重復,而且難以單元測試。我們希望action的簽名類似以下的形式:
public object MyAction(int id, Customer c) { }
那麼WebAPI是如何將request message轉換成像id和customer這樣的參數的呢?
Model Binding vs. Formatters
參數綁定有兩種技術:Model Binding和Formatters。實際上,WebAPI使用model binding讀取查詢字元串(query string)內容進行參數綁定,使用Formatters讀取主體內容
(body content)進行參數的綁定。
Using Model Binding:
ModelBinding和MVC中的此概念是一致的,更多內容見Here。通常有一個"ValuePeoviders"提供數據片斷如查詢字元串參數,model binder將這些片斷組合成一個對象。
Using Formatters:
Formatters(如MediaTypeFormatter類所示)實際上是包含額外元數據的序列化程序。WebAPI從HttpConfiguration中獲取一個formatters的列表,然後通過request信息
中的content-type來判斷採用具體合適的formatter。WebAPI有不少默認的formatters。默認的JSON formatter是JSON.NET。還有Xml formatter和採用JQuery語法的
FormUrl formatter。
其中Formatters的核心方法是MediaTypeFormatter.ReadFromStreamAsync,如下所示:
public virtual Task..

❽ 怎樣操作WebAPI介面

先定義一個簡單的webapi,簡單到差不多直接用vs2010自動生成的webapi代碼。
其中的TestModle是一個簡單的class,如下
public class TestModle
{
public string a { get; set; }
public string b { get; set; }
public string c { get; set; }
}

前端頁面放四個代表get,post,put,delete的按鈕,在加一個div顯示返回值

前端代碼中載入jquery,在定義四個按鈕的click事件

get和post,我習慣用$.get和$.post,當然也能用$.ajax.
get直接返回webapi get的return值,post的話我就不在後端做處理了直接返回傳入的值,這里只做示範

put和delete,只能用$.ajax來處理。
put的話一般用於update某個id的數據信息

delete用於刪除某個id的數據,如下圖所示

點擊每個按鈕,可以在頁面上看到相應的效果