WebAPI 2 - 建立自訂Http
Response訊息
上一篇文章建立第一支Web Api 2,提到了WebAPI 2 的Attribute Routing, 這邊則是介紹另外一個新功能:利用
IHttpActionResult 來建立自訂的Response訊息。
1.
先看一下IHttpActionResult這個interface
在IHttpActionResult – new way of creating responses in ASP.NET Web API 2說明得很詳細它的作用,底下是簡短節錄其中的解釋:
「Instead of returning an instance of an object or a raw HttpResponseMessage, you can return IHttpActionResult and Web API will follow your instructions coded in there.」
我們在接下來的範例,會介紹如何去修改Http Response 訊息的Header和Content。
在IHttpActionResult – new way of creating responses in ASP.NET Web API 2說明得很詳細它的作用,底下是簡短節錄其中的解釋:
「Instead of returning an instance of an object or a raw HttpResponseMessage, you can return IHttpActionResult and Web API will follow your instructions coded in there.」
我們在接下來的範例,會介紹如何去修改Http Response 訊息的Header和Content。
2.
新增一個類別:CreatedActionResult
並實作IHttpActionResult
public class CreatedActionResult:IHttpActionResult
{
private readonly HttpRequestMessage request;
並實作IHttpActionResult
public class CreatedActionResult:IHttpActionResult
{
private readonly HttpRequestMessage request;
//Header
private String location;
private String serivceProvider;
//Content
private ByteArrayContent content = null;
/// <summary>
/// 建構子
/// </summary>
public CreatedActionResult(HttpRequestMessage _request)
{
this.request = _request;
}
/// <summary>
/// 設定Header值
/// </summary>
/// <param
name="location"></param>
/// <param
name="serivceProvider"></param>
public void SetHeader(String _location, String _serivceProvider)
{
this.location = _location;
this.serivceProvider = _serivceProvider;
}
/// <summary>
/// 設定Content
/// </summary>
/// <param
name="_byteData"></param>
public void SetContent(Byte[] _byteData)
{
this.content = new ByteArrayContent(_byteData);
this.content = new ByteArrayContent(_byteData);
}
/// <summary>
/// 設定 Reponse 訊息
/// </summary>
/// <param
name="cancellationToken"></param>
/// <returns></returns>
public Task<HttpResponseMessage> ExecuteAsync(
CancellationToken cancellationToken)
{
try
{
///設定Reponse的HttpStatusCode
var response = this.request.CreateResponse(HttpStatusCode.Accepted); //202
///設定Reponse的Header
response.Headers.Location = new Uri(this.location);
response.Headers.Add("ServiceProvider", this.serivceProvider);
///設定Reponse的Content
response.Content = this.content;
///Return
return Task.FromResult(response);
}
catch (Exception ex)
{
throw new Exception("自行設定HttpActionResult錯誤:" + ex.Message);
}
}
}
u 上面的程式碼主要是利用實作IHttpActionResult去修改Response的Http
Status code、Header內容(修改location、新增serivceProvider資訊)以及Content內容。
3.
我們先建立一個PUT方法,看一下正常的Reponse內容。 (以PUT為例,實際可使用任何CRUD)
這邊我先建立一個簡單的Class:MyData
public class MyData
{
public int NumA;
public int NumB;
public int Result;
public int Sum()
{
Result = NumA + NumB;
return _rslt;
}
}
在ValuesController建立一個一般的PUT方法。
public MyData Put(MyData _data)
{
_data.Sum();
return _data;
}
實際執行測試後,收到的Response:
這邊我先建立一個簡單的Class:MyData
public class MyData
{
public int NumA;
public int NumB;
public int Result;
public int Sum()
{
Result = NumA + NumB;
return _rslt;
}
}
在ValuesController建立一個一般的PUT方法。
public MyData Put(MyData _data)
{
_data.Sum();
return _data;
}
實際執行測試後,收到的Response:
4.
接下來,我們修改上面的PUT方法,使其回傳CreatedActionResult物件。
// PUT api/values
public CreatedActionResult Put(MyData _data)
{
///將要回覆的Content值轉換為ByteArray
Byte[] myByte = Encoding.ASCII.GetBytes(
String.Format("Result = {0}", _data.Sum().ToString())
);
///宣告IHttpActionResult
CreatedActionResult _rslt = new CreatedActionResult( Request);
//設定Header
_rslt.SetHeader(
_location:Url.Link("DefaultApi", new { controller = "values", id = "Data物件" }),
_serivceProvider: "I am Web API 2"
);
//設定Content
_rslt.SetContent(myByte);
return _rslt;
}
// PUT api/values
public CreatedActionResult Put(MyData _data)
{
///將要回覆的Content值轉換為ByteArray
Byte[] myByte = Encoding.ASCII.GetBytes(
String.Format("Result = {0}", _data.Sum().ToString())
);
///宣告IHttpActionResult
CreatedActionResult _rslt = new CreatedActionResult( Request);
//設定Header
_rslt.SetHeader(
_location:Url.Link("DefaultApi", new { controller = "values", id = "Data物件" }),
_serivceProvider: "I am Web API 2"
);
//設定Content
_rslt.SetContent(myByte);
return _rslt;
}
u Return a CreatedActionResult object。
u 建立CreatedActionResult所需要的資訊。
5.
Reference:
IHttpActionResult
– new way of creating responses in ASP.NET Web API 2
ASP.NET Web API 2 – Web Services for Websites, Modern Apps, and Mobile Apps (Build 2013)
ASP.NET Web API 2 – Web Services for Websites, Modern Apps, and Mobile Apps (Build 2013)
沒有留言:
張貼留言