ASP.NET Web API queryString訪問的一點總結

來源:互聯網
上載者:User

標籤:http   ar   io   os   使用   sp   for   on   檔案   

自從開始使用ASP.NET Web API,各種路由的蛋疼問題一直困擾著我,相信大家也都一樣。

Web API的路由配置與ASP.MVC類似,在App_Start檔案夾下,有一個WebApiConfig類檔案 config.Routes.MapHttpRoute(    name: "DefaultApi",    routeTemplate: "api/{controller}/{id}",    defaults: new { id = RouteParameter.Optional });以上為一個空Web API項目的路由配置。 我們建立一個Controller public class TestRouteController : ApiController{    public HttpResponseMessage GetUser(int id)    {        return Request.CreateResponse(HttpStatusCode.OK, new        {            status = "success",            data = new { Id = id, Name = "使用者" + id }        });    }}按照msdn所述 To find the action, Web API looks at the HTTP method, and then looks for an action whose name begins with that HTTP method name. For example, with a GET request, Web API looks for an action that starts with "Get...", such as "GetContact" or "GetAllContacts". This convention applies only to GET, POST, PUT, and DELETE methods. You can enable other HTTP methods by using attributes on your controller. We’ll see an example of that later. Web API 約定了,如果方法名帶有Get,則為Get請求,其他請求方式同樣道理當然,我們也可以使用HttpGet、HttpPost等特性,或者AcceptVerbs("GET","POST",...)等等,來控制我們的請求方式。 根據路由配置,我們可以理解,我們的訪問地址應為:api/TestRoute/123,請求方式為GET   毫無疑問的,我們拿到了想要的結果:{"status":"success","data":{"Id":123,"Name":"使用者123"}} 按照我們之前MVC路由的理解,路由中,new { id = RouteParameter.Optional }表示id參數是選擇性參數,我們期望的,在沒有id傳入的情況下,地址可以正常訪問,id為預設值0。 很遺憾,直接404了。 我們簡單改動一下代碼 public HttpResponseMessage GetUser(int id = 0){    return Request.CreateResponse(HttpStatusCode.OK, new    {        status = "success",        data = new { Id = id, Name = "使用者" + id }    });}我們將方法參數id設定了一個預設值,居然成功了  我們再變一種訪問方式,api/TestRoute/?id=123在有參數的情況下,是可以正常訪問的。而訪問api/TestRoute/?id=,則會出現 {"Message":"請求無效。","MessageDetail":"對於“WebApiTest.Controllers.TestRouteController”中方法“System.Net.Http.HttpResponseMessage GetUser(System.DateTime)”的不可為 Null 的型別“System.DateTime”的參數“time”,參數字典包含一個 null 項。選擇性參數必須為參考型別、可為 Null 的型別或聲明為選擇性參數。"}的400錯誤。將id參數設定為int?類型,我們訪問http://localhost:62488/api/TestRoute/?id=則可正常訪問,並且此時id為null。 經過以上的測試,我們是否可以得出結論: 在ASP.NET Web API中,並且我們熟知的C# int未賦值時預設0,bool未賦值時預設false等在此都是不適用的如果請求的參數在方法上定義,則參數名必須拼接在訪問地址上 我們再試一種情況,我們將需要傳入的參數放到一個類中,在方法上直接傳入這個參數對象 public class QueryParams{    public int Id { get; set; }     public string Name { get; set; }} public HttpResponseMessage GetUser(QueryParams queryParams){    return Request.CreateResponse(HttpStatusCode.OK, new    {        status = "success",        data = new { Id = queryParams.Id, Name = "使用者:" + queryParams.Name }    });        }直接存取api/TestRoute/,我們會發現,不管我們是否傳入參數,我們的參數對象都是null。  這時候我們需要為我們的參數對象添加一個FromUri的特性,來告訴web api,我們這個對象的中屬性都是從url連結上傳過來的 這時候依舊不傳入任何參數,卻驚奇的發現,我們的對象參數不再是null,其中屬性的值也與我們料想的一致(C# int未賦值時預設0,string預設null)  經過這進一步的嘗試,我們可以完善我們的結論 通過queryString方法拼接參數時 如果請求的參數為C#文法定義的類型,且在方法上定義,則參數名必須拼接在訪問地址上如果請求的參數為一個實體類,則需要為該參數添加[FromUri]的特性。

ASP.NET Web API queryString訪問的一點總結

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.