C# Json Xml 輸出 Controller
//輸出功能
public class BasicClass
{
public static HttpResponseMessage outConnection<T>(T mainData, string outputType)
{
var returnDaat = new HttpResponseMessage(HttpStatusCode.OK);
if (outputType == "xml") //確認輸出格式
{
returnDaat.Content = new ObjectContent<T>(mainData, new XmlMediaTypeFormatter()); //xml
}
else
{
returnDaat.Content = new ObjectContent<T>(mainData, new JsonMediaTypeFormatter()); //json
}
return returnDaat;
}
}
//Controller
public class TestController : ApiController
{
[HttpPost]
[ActionName("Data1")]
public HttpResponseMessage TestControllersData01([FromBody]InModel jasonData)
{
List<OutModel> mainData = new List<OutModel>(); //宣告資料格式
featuresClass feature = new featuresClass();
mainData = feature.testFeatureData01(jasonData); //呼叫主程式
var returnData = BasicClass.outConnection(mainData, jasonData.outputType);
return returnData;
}
//其他功能...
}
//定義輸入輸出Model
namespace MspApi.Models.Model
{
public class InModel
{
public string userId { get; set; } //查詢帳號
public string outputType { get; set; } //輸出類型 json xml
}
public class OutModel
{
public string userName { get; set; } //資料結果
public string userData { get; set; } //資料結果
}
}
//主程式Model
namespace MspApi.Models.API
{
public class featuresClass
{
public List<OutModel> testFeatureData01(InModel jasonData)
{
List<OutModel> returnDaat = new List<OutModel>(); //宣告資料格式
//主程式碼...
return returnDaat;
}
//其他功能...
}
}
備註:這只是一個簡易的範例,該加入判斷式的,是否登入,是否有權限等等...請自行補上!
我只是一棵樹