对于从Web API 2控制器返回,如果响应是OK(状态200),我可以返回内容与响应:
public IHttpActionResult Get()
{
string myResult = ...
return Ok(myResult);
}
如果可能的话,我希望在这里尽可能使用内置结果类型
我的问题是,对于另一种类型的响应(不是200),我如何用它返回消息(字符串)?例如,我可以这样做:
public IHttpActionResult Get()
{
return InternalServerError();
}
但这不是:
public IHttpActionResult Get()
{
return InternalServerError("Message describing the error here");
}
理想情况下,我希望这是一般化的,这样我就可以用IHttpActionResult的任何实现发送回消息。
我需要这样做(并建立我的响应消息):
public IHttpActionResult Get()
{
HttpResponseMessage responseMessage = ...;
return ResponseMessage(responseMessage);
}
还是有更好的办法?
我也有同样的问题。我想为我的api控制器创建自定义结果,像这样调用它们
return Ok("some text");
然后我这样做了:
1)使用singletone创建自定义结果类型
public sealed class EmptyResult : IHttpActionResult
{
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NoContent) { Content = new StringContent("Empty result") });
}
}
2)使用new方法创建自定义控制器:
public class CustomApiController : ApiController
{
public IHttpActionResult EmptyResult()
{
return new EmptyResult();
}
}
然后我可以在我的控制器中调用它们,像这样:
public IHttpActionResult SomeMethod()
{
return EmptyResult();
}
下面的代码/类确实有助于处理所有类型的响应。可能是成功或失败等。
为什么要用这个?:
假设我正在使用web API服务。输出有如下几种可能性:
由于验证错误,您可能得不到任何结果
你会得到预期的结果
你会得到错误。
So here I have solution to handle all the scenarios. Also I tried to maintain uniformity in the output. You can give remark or actual error message. The web service consumer can only check IsSuccess true or not else will sure there is problem, and act as per situation. There should be perfect communication between web API developer and web API consumer. If result is not generating then why. The comment or exception will acknowledge and they will act accordingly.
Hence this is best solution for web API consumer / user.
对所有类型的结果进行单一响应。
public class Response
{
/// <summary>
/// Gets or sets a value indicating whether this instance is success.
/// </summary>
/// <value>
/// <c>true</c> if this instance is success; otherwise, <c>false</c>.
/// </value>
public bool IsSuccess { get; set; } = false;
/// <summary>
/// Actual response if succeed
/// </summary>
/// <value>
/// Actual response if succeed
/// </value>
public object Data { get; set; } = null;
/// <summary>
/// Remark if anythig to convey
/// </summary>
/// <value>
/// Remark if anythig to convey
/// </value>
public string Remark { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the error message.
/// </summary>
/// <value>
/// The error message.
/// </value>
public object ErrorMessage { get; set; } = null;
}
[HttpGet]
public IHttpActionResult Employees()
{
Response _res = new Response();
try
{
DalTest objDal = new DalTest();
_res.Data = objDal.GetTestData();
_res.IsSuccess = true;
return Request.CreateResponse(HttpStatusCode.OK, _res);
}
catch (Exception ex)
{
_res.IsSuccess = false;
_res.ErrorMessage = ex;
return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, _res ));
}
}
如有任何建议,欢迎您提出:)
如果有人使用并从中受益,我很高兴。如果有任何增加或修改使这更完善,请在akhandagale65@gmail.com上写信给我。
一个更详细的示例,支持在c# HttpStatusCode中未定义的HTTP代码。
public class MyController : ApiController
{
public IHttpActionResult Get()
{
HttpStatusCode codeNotDefined = (HttpStatusCode)429;
return Content(codeNotDefined, "message to be sent in response body");
}
}
Content是在抽象类ApiController(控制器的基类)中定义的虚方法。声明如下:
protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value);