天天看點

.net WebApi 開發中某些注意事項

目前在做.net開發。

需要開發一套webapi.

這裡記錄一下某些注意點。

1. 如何開啟跨域

如果webapi的使用者是域外使用者,則需要根據需要開放跨域。

首先安裝Install-Package Microsoft.AspNet.WebApi.Cors

在WebApiConfig.cs裡開啟config.EnableCors();

可以控制開放的範圍,例如隻開放某些controller,還是全局都開發等到。

參考:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

2.接收json

webapi一般接收Json。這個不困難,送給某些需要的人。

$.ajax({
url: "*****/Account/Login",
type: "POST",
data: JSON.stringify({UserName:'user1',Password:'123456'}),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
console.log(response.responseText);
},
success: function (response) {
console.log(response);
}
});      

參考http://stackoverflow.com/questions/21578814/how-to-receive-json-in-a-mvc-5-action-method-as-a-paramter 

3. 上傳檔案

webapi的檔案上傳和mvc不一樣。

具體方式自己選擇,可以參考

http://weblog.west-wind.com/posts/2012/Sep/11/Passing-multiple-simple-POST-Values-to-ASPNET-Web-API      

 和

http://blogs.msdn.com/b/codefx/archive/2012/02/23/more-about-rest-file-upload-download-service-with-asp-net-web-api-and-windows-phone-background-file-transfer.aspx      

 提醒一點,檔案在controller裡面必須使用[FromUri]屬性,否則報錯:

No MediaTypeFormatter is available to read an object of type 'HttpPostedFileBase[]' from content with media type 'multipart/form-data'.      

如果選擇使用js來上傳,請參考

http://www.codeproject.com/Articles/806075/File-Upload-using-jQuery-AJAX-in-ASP-NET-Web-API      

 apicontroller的request沒有files這個屬性,需要使用HttpContext.Current.Request.Files

繼續閱讀