Ⅰ WebAPI 怎樣獲取相對路徑 獲取本地路徑
其實這個方法就是Controller實例下的一個屬性(但不是apiController),因此我們實例化一個Controller就行了。
如下即可:
[csharp] view plain
System.Web.Mvc.Controller controller = new HomeController();
var curProjRootPath = controller.Server.MapPath("~/");
Ⅱ webapi的webconfig怎樣配置資料庫連接
先打開vs2010軟體,找到項目文件,雙擊web.config
VS2010中web.config配置資料庫連接
第一種:取連接字元串
string connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["sqlConnStr"].ConnectionString;
或者
protected static string connectionString = ConfigurationManager.ConnectionStrings["SqlConnStr"].ConnectionString;
web.config文件:加在</configSections>後面
<connectionStrings> <remove name="LocalSqlServer" /> <add name="SqlConnStr" connectionString="user id=xx;password=xx;initial catalog=database_name;data source=.\sqlxxxx" /> </connectionStrings>
VS2010中web.config配置資料庫連接
第二種:取連接字元串:
string myvar=configurationsettings.appsettings["connstring"];
web.config文件:加在<appsettings>和</appsettings> 之間
<appsettings> <add key="connstring" value="uid=xx;pwd=xx;database=batabase_name;server=(local)" /> </appsettings>
據說兩者通用,但是第二種是asp.net2.0的新特性,建議使用第二種。其實咱一直有個疑問,兩個字元串中的UID;PWD;和User ID; Password;是否等價。根據網上查到的資料是可以互換通用的。
VS2010中web.config配置資料庫連接
連接SQL Server資料庫的機制與連接Access的機制沒有什麼太大的區別,只是改變了Connection對象和連接字元串中的不同參數.
首先,連接SQL Server使用的命名空間不是"System.Data.OleDb",而是"System.Data.SqlClient".
其次就是他的連接字元串了,咱們一個一個參數來介紹(注意:參數間用分號分隔): "user id=sa":連接資料庫的驗證用戶名為sa.他還有一個別名"uid",所以這句還可以寫成"uid=sa". "password=":連接資料庫的驗證密碼為空.他的別名為"pwd",所以可以寫為"pwd=". 這里注意,自己的SQL Server必須已經設置了需要用戶名和密碼來登錄,否則不能用這樣的方式來登錄.如果自己的SQL Server設置為Windows登錄,那麼在這里就不需要使用"user id"和"password"這樣的方式來登錄,而需要使用"Trusted_Connection=SSPI"來進行登錄.
initial catalog=Northwind":使用的數據源為"Northwind"這個資料庫.他的別名為"Database",本句可以寫成"Database=Northwind". "Server=YourSQLServer":使用名為"YourSQLServer"的伺服器.他的別名為"Data Source","Address","Addr".如果使用的是本地資料庫且定義了實例名,則可以寫為"Server=(local)\實例名";如果是遠程伺服器,則將"(local)"替換為遠程伺服器的名稱或IP地址. "Connect Timeout=30":連接超時時間為30秒.
在這里,建立連接對象用的構造函數為:SqlConnection.
7
最後要保存所更改的文件,右鍵 保存(ctrl+S).
Ⅲ .net web api實例應該如何寫
由於我機器裝的是win8企業版操作系統,VS版本是2012,因此我們選擇使用VS自帶的MVC4模版中的Web API來創建一個項目。
點擊確定後,VS會自動為我們創建一個完整的可運行的ASP.NET Web API的項目。
從項目的目錄結構可以看出,ASP.NET Web API與ASP.NET MVC項目的結構幾乎一致。我們刪除為我們默認創建並打開的ValuesController文件(示例性文件,可以參考)。
既然要打造一個IP地址查詢服務介面,為了跟上文的服務形式一致,我們還是使用GET請求方式的服務,不過我們這次使用MVC中的Web API來實現。
首先在Models文件夾中建立一個Address模型類。
?
1
2
3
4
5
6
7
8
9
namespace MvcWebApi.Models
{
public class Address
{
public string IPAddress { get; set; }
public string Province { get; set; }
public string City { get; set; }
}
}
接著我們在Controllers文件夾下建立一個IPAddressController控制器,需要注意的是,這個IPAddressController一定要繼承自ApiController類,這樣服務才能暴露出來。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace MvcWebApi.Controllers
{
public class IPAddressController : ApiController
{
private static IList addresses = new List
{
new Address(){ IPAddress="1.91.38.31", Province="北京市", City="北京市" },
new Address(){ IPAddress = "210.75.225.254", Province = "上海市", City = "上海市" },
};
public IEnumerable GetIPAddresses()
{
return addresses;
}
public Address GetIPAddressByIP(string IP)
{
return addresses.FirstOrDefault(x => x.IPAddress == IP);
}
}
}</address></address></address>
只要做上面兩步就可以運行這個項目了,我們按Ctrl+F5運行整個項目,出現了如下的頁面。
我們點擊右上角的API鏈接。
可以看到我們定義的Web API的介面的使用方法以及說明。
既然是服務,能夠被其它程序調用就需要一個持續保障它運行的環境,我們可以將這個寫好的Web API的項目發布到IIS當中。
我們可以使用VS自帶的發布功能進行發布,並映射到IIS應用程序目錄當中。
我們點擊IIS右側的瀏覽,看看服務有沒有能夠正常運行。
我們按照文檔的提示,我們在地址欄輸入http://192.168.0.2/webapi/api/ipaddress。
可以看到,我們收到了Web API定義的服務提供的數據。同樣的我們試一下另外一個介面方法。
OK,這樣就好了。
但是如果我們需要返回JSON格式怎麼辦呢?有個簡便的方法,在Global.asax.cs文件中,添加一個方法即可。
關於這段代碼的原因,可以參考:http://blog.miniasp.com/post/2012/10/12/ASPNET-Web-API-Force-return-JSON-format-instead-of-XML-for-Google-Chrome-Firefox-Safari.aspx,這里不重復。
我們運行這個項目後,重復發布。
當我們再次在瀏覽器中運行時,就可以看到默認返回的是JSON格式了(IE默認就是JSON)。
ASP.NET Web API就開發好了,至於在C#程序中怎麼調用,可以參考我上篇博客中的代碼。如果要在頁面中調用,可以通過jQuery等JS庫請求URL即可。
Ⅳ 如何使用mvc實現webapi的增刪改查
1.創建項目:visual C# —> ASP.NET MVC 4 web應用程序 模板—>web api;
2.注冊路由:
路由表中的每一個條目都包含一個路由模板。這個Web API默認的路由模版是"api/{controller}/{id}"。在這個模版中,「api」是一個文字式路徑片段,而{controller}和{id}則是佔位符變數。
當Web API框架接收一個HTTP請求時,它會試圖根據路由表中的一個路由模板來匹配其URI。如果無路由匹配,客戶端會接收到一個404(未找到)錯誤。
3.linq to sql連接資料庫
1.建立資料庫建表
2.在models文件夾裡面新建linq to sql類文件
3.工具->連接到資料庫
4.將要用的表拖入設計區
5.獲取資料庫Getway。"linq to sql class"文件名+Datacontext實例化這個對象,數據表就會映射到一個集合屬性中,personDataDataContext db = new personDataDataContext();
6.增刪改查
增:
public Boolean Post([FromBody]UserInfo userInfo) {
personDataDataContext db = new personDataDataContext();
var s1 = new test2
{
UserName =userInfo.UserName, Id=userInfo.Id, Age=userInfo.Age
};
if (db.test2.SingleOrDefault<test2>(s => s.Id == userInfo.Id) == null)
{
db.test2.InsertOnSubmit(s1);
db.SubmitChanges();
return true;
} else {
return false;
}
}
刪:
public bool Delete(int id)
{
personDataDataContext db = new personDataDataContext();
var deleteperson = db.test2.SingleOrDefault<test2>(s => s.Id == id);
if (deleteperson == null)
{
return false;
} else {
db.test2.DeleteOnSubmit(deleteperson);
db.SubmitChanges();
return true;
}
}
改:
public Boolean Put(int id, [FromBody]UserInfo userInfo)
{
personDataDataContext db = new personDataDataContext();
var editperson = db.test2.SingleOrDefault<test2>(s => s.Id == userInfo.Id);
if (editperson == null)
{
return false;
} else {
editperson.Age = userInfo.Age;
editperson.UserName = userInfo.UserName;
db.SubmitChanges();
return true;
}
查:
public IEnumerable<test2> Get()
{
personDataDataContext db = new personDataDataContext();
var query = from s in db.test2
orderby s.UserName
select s;
return query;
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
這里我新建了一個userinfo類
public class UserInfo { public string UserName { get; set; } public int Id { get; set; } public int Age { get; set; } }
用來接收前端頁面ajax請求中的data數據,s => s.Id == userInfo.Id是lamda表達式創建委託方法意思是在db.test2的person集合中查找某個person的Id與userinfo接收到的id相等的person對象
Ⅳ webapi filter 每一個請求都是相同的實例嗎
在webapi項目中新建一個MyTestFilter類 這里需要重寫兩個方法 OnActionExecuting 執行前調用 OnActionExecuted 執行後調用 可以把aop操作寫在相應的方法中 這里就不解釋具體的aop操作了,
Ⅵ c# webapi中優先過濾post參數(求代碼實例)
用 if(sign滿足){return 處理後結果} return 默認信息 就可以了
Ⅶ webapi同時支持get和post 怎麼接受多個參數
這里給出一個實例,僅供參考:
[csharp] view plain
[AcceptVerbs("Get", "Post")] //用AcceptVerbs標識即可
public List<PUB_HqewIndexResult> GetSalesRankByHqewIndex()
{
List<PUB_HqewIndexResult> resultList = new List<PUB_HqewIndexResult>();
DMSParam dmsParam = new DMSParam();
List<PUB_Stock> stockList = new List<PUB_Stock>();
IResult stockResult = ExecuteDmsParam(dmsParam, new PUB_HqewIndex(), "PUB.PUB_HqewIndexBLL", "GetSalesRankByHqewIndex");
if (stockResult.Complete == DMSComplete.Succeed)
{
if (stockResult != null && stockResult.Result != null)
{
resultList = (List<PUB_HqewIndexResult>)stockResult.Result;
}
}
return resultList;
}
Ⅷ 怎樣用webapi連接到資料庫的數據
先打開vs2010軟體,找到項目文件,雙擊web.config
vs2010中web.config配置資料庫連接
第一種:取連接字元串
string
connstring
=
system.web.configuration.webconfigurationmanager.connectionstrings["sqlconnstr"].connectionstring;
或者
protected
static
string
connectionstring
=
configurationmanager.connectionstrings["sqlconnstr"].connectionstring;
web.config文件:加在</configsections>後面
<connectionstrings>
<remove
name="localsqlserver"
/>
<add
name="sqlconnstr"
connectionstring="user
id=xx;password=xx;initial
catalog=database_name;data
source=.\sqlxxxx"
/>
</connectionstrings>
vs2010中web.config配置資料庫連接
第二種:取連接字元串:
string
myvar=configurationsettings.appsettings["connstring"];
web.config文件:加在<appsettings>和</appsettings>
之間
<appsettings>
<add
key="connstring"
value="uid=xx;pwd=xx;database=batabase_name;server=(local)"
/>
</appsettings>
據說兩者通用,但是第二種是asp.net2.0的新特性,建議使用第二種。其實我一直有個疑問,兩個字元串中的uid;pwd;和user
id;
password;是否等價。根據網上我查到的資料是可以互換通用的。
vs2010中web.config配置資料庫連接
連接sql
server資料庫的機制與連接access的機制沒有什麼太大的區別,只是改變了connection對象和連接字元串中的不同參數.
首先,連接sql
server使用的命名空間不是"system.data.oledb",而是"system.data.sqlclient".
其次就是他的連接字元串了,我們一個一個參數來介紹(注意:參數間用分號分隔):
"user
id=sa":連接資料庫的驗證用戶名為sa.他還有一個別名"uid",所以這句我們還可以寫成"uid=sa".
"password=":連接資料庫的驗證密碼為空.他的別名為"pwd",所以我們可以寫為"pwd=".
這里注意,你的sql
server必須已經設置了需要用戶名和密碼來登錄,否則不能用這樣的方式來登錄.如果你的sql
server設置為windows登錄,那麼在這里就不需要使用"user
id"和"password"這樣的方式來登錄,而需要使用"trusted_connection=sspi"來進行登錄.
initial
catalog=northwind":使用的數據源為"northwind"這個資料庫.他的別名為"database",本句可以寫成"database=northwind".
"server=yoursqlserver":使用名為"yoursqlserver"的伺服器.他的別名為"data
source","address","addr".如果使用的是本地資料庫且定義了實例名,則可以寫為"server=(local)\實例名";如果是遠程伺服器,則將"(local)"替換為遠程伺服器的名稱或ip地址.
"connect
timeout=30":連接超時時間為30秒.
在這里,建立連接對象用的構造函數為:sqlconnection.
7
最後要保存你所更改的文件,右鍵
保存(ctrl+s).
Ⅸ webapi httpcontent怎麼實例化
public class ValueProvider : IValueProvider
{
private IEnumerable<KeyValuePair<string, string>> _queryParameters;
private HttpContent _httpContent;
private HttpActionContext _context;
public ValueProvider(HttpActionContext context)
{
_context = context;
_httpContent = context.Request.Content;
_queryParameters = context.Request.GetQueryNameValuePairs();
}
public bool ContainsPrefix(string prefix)
{
return _queryParameters.Any(x => x.Key == prefix);
}
NameValueCollection _formDatas = (NameValueCollection)CallContext.LogicalGetData("$formDatas");
public ValueProviderResult GetValue(string key)
{
var value = _queryParameters.FirstOrDefault(x => x.Key == key).Value;
if (string.IsNullOrWhiteSpace(value))
{
if (_formDatas == null)
{
if (_httpContent.IsFormData())
{
if (_formDatas == null)
{
_formDatas = _httpContent.ReadAsFormDataAsync().Result;
CallContext.LogicalSetData("$formDatas", _formDatas);
}
}
else
{
throw new HttpResponseException(_context.Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, string.Format("未在URL中找到名為{0}的參數,此時必須傳入表單參數或json或xml參數", key)));
}
}
value = _formDatas[key];
if (string.IsNullOrWhiteSpace(value))
{
throw new HttpResponseException(_context.Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, string.Format("未在URL中找到名為{0}的參數,也未在表單中找到該參數", key)));
}
}
return new ValueProviderResult(value, value, CultureInfo.InvariantCulture);
}
}
Ⅹ 在WebApi中返回一個JSON格式的數據,如何到客戶端就變了
轉載 在使用Web Api的時候,有時候只想返回JSON;實現這一功能有多種方法,本文提供兩種方式,一種傳統的,一種作者認為是正確的方法。
JSON in Web API – the formatter based approach
只支持JSON最普遍的做法是:首先清除其他所有的formatters,然後只保留JsonMediaTypeFormatter。
有了HttpConfiguration的實例,你將會很簡單的清除所有formatters,然後重新添加JsonMediaTypeFormatter。
實現代碼如下:
configuration.Formatters.Clear();
configuration.Formatters.Add(new JsonMediaTypeFormatter());這種方式雖然可以實現功能,但是所有的conent negotiation還是會發生,這就會產生以下額外的開銷了。因為,你已經知道要返回的結果了,也只想返回Json,其他的content negotiation都不需要了。
下面的方法可以很好的解決這個問題。
JSON in Web API – the conneg based approach
最好的方法是使用自定義的只返回Json Result的content negotiation代替Web Api中默認的content negotiation。
Conneg通過實現IContentNegotiator的Negotiator方法實現擴展。Negotiator方法返回ContentNegotiationResult(它包裝了你選擇的headers和formatter)。
下面的方法通過傳遞一個JsonMediaTypeFormatter給自定義的conneg negotiator,讓它一直返回applicaton/json 的content-type以及JsonMediaTypeFormatter。這種方法避免了每次請求都要重新創建一次formatter。
代碼如下:
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}接下來,你需要在HttpConfiguration實例上注冊你的新的實現機制:
var jsonFormatter = new JsonMediaTypeFormatter();
//optional: set serializer settings here
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
通過替換默認的DefaultContentNegotiator,我們使用我們自定義的JsonContentNegotiator,它只支持Json,而且可以馬上返回。
如果你想更深入的了解Content Negotiation的知識,你可以查看作者的這篇文章。
總結
通過使用自定義的JsonContentNegotiator替換系統默認的DefaultContentNegotiator,很好的實現Web Api只返回Json的功能,而且沒有額外的開銷。