在ASP.NET應用MVC4 JSON網絡API服務像長期和代碼的URL參數要求:與代碼和術語查詢請求創建Web參數API需要創建
http://myapp.com/api/customers
回報所有客戶
http://myapp.com/api/customers?term=partofname
返回0 ... N的客戶
和
http://myapp.com/api/customers?code=customercode
返回1,客戶總會
代碼是客戶ID可以包含/等字符未在 URL傳遞到Windows HTTP服務器通過HTTP.SYS Windows內核中允許
下面的API控制器被嘗試,但它導致編譯錯誤
錯誤類型'Erp.Controllers.CustomersController'已經定義了一個名爲'Get'的成員具有相同的參數呃類型。
如何解決這個問題? 哪種方法可以爲這樣的請求創建API類? 應該使用odata還是使用不同的方法名稱或其他方式? 應用程序必須在Windows 2003服務器和Mono中運行,因此Web API v.2無法使用。
如果有幫助,方法和查詢字符串參數名稱可以更改。返回的數據格式無法更改。
public class CustomersController : ApiController
{
public object Get()
{
var res = GetAllCustomers();
return Request.CreateResponse(HttpStatusCode.OK,
new { customers = res.ToArray() });
}
public object Get(string term)
{
var res = GetCustomersByTerm(term);
return Request.CreateResponse(HttpStatusCode.OK,
new { customers = res.ToArray() });
}
public object Get(string code)
{
var res = GetCustomersById(code);
// code is actually unique customer id which can contain/and other characters which are not allowed in
// url directory names in windows http server
return Request.CreateResponse(HttpStatusCode.OK,
new { customers = res.ToArray() });
}
}
默認路由使用:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
更新
我試着回答,但搜索參數始終是零。 整個要求如下。如何傳遞參數?
GET /api/customers?term=kaks&_=1385320904347 HTTP/1.1
Host: localhost:52216
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36
Referer: http://localhost:52216/erp/Sale
Accept-Encoding: gzip,deflate,sdch
Accept-Language: et-EE,et;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: .myAuth=8B6B3CFFF3DF64EBEF3D258240D217C56603AF255C869FBB7934560D9F560659342DC4D1EAE6AB28454122A86C3CE6C598FB594E8DC84A; My_Session=5aw2bsjp4i4a5vxtekz
作爲問題描述的,客戶代碼可以包含/,*%和其他字符這是不允許的url目錄名稱。在Windows中,kernel.sys立即返回錯誤的請求錯誤,並且不會將它傳遞給IIS。在這種情況下,如何在您的答案中使用REST風格的最後一個API鏈接示例? – Andrus
如果客戶代碼可能包含此類危險字符,則它們不屬於網址的路徑部分。它們應該被用作查詢字符串參數。留下他們作爲查詢字符串,並採用我的答案中所示的方法,或選擇一個更好的屬性來識別客戶而不是此代碼。 –
我試過這個,但搜索始終爲空。我更新了問題。怎麼修? – Andrus