以下範例為,藉由 web api 吐出 xml 格式來示範 HttpResponseMessage、HttpStatusCode 的用法。
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 += "<?xmlversion=\"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 的差異
沒有留言:
張貼留言