web api xml 範例 HttpResponseMessage、HttpStatusCode 的使用

 

以下範例為,藉由 web api 吐出 xml 格式來示範 HttpResponseMessage、HttpStatusCode 的用法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebApplication1.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class personalTestController : ApiController
{
[HttpPost]
public HttpResponseMessage CreateEvent()
{
string result = "";
result += "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
result += "<bookstore>";
result += " <book>";
result += " <title>Everyday Italian</title>";
result += " <author>Giada De Laurentiis</author>";
result += " <year>2005</year>";
result += " </book>";
result += "</bookstore>";

return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(result, System.Text.Encoding.UTF8, "application/xml")
};
}
}
}

參考資料:
[Web API] 使用 HttpResponseMessage 與 HttpResponseException 的差異