Asp.net mvc 4 MVC WebApi。要根据当前格式化程序获取HttpResponseMessage的格式吗
下面是我获取MVC Web Api RC的方法Asp.net mvc 4 MVC WebApi。要根据当前格式化程序获取HttpResponseMessage的格式吗,asp.net-mvc-4,asp.net-web-api,Asp.net Mvc 4,Asp.net Web Api,下面是我获取MVC Web Api RC的方法 public Employee Get(int id) { Employee emp= null; //try getting the Employee with given id, if not found, gracefully return error message with notfound status if (!_repository.TryGet(id, out emp)) thro
public Employee Get(int id)
{
Employee emp= null;
//try getting the Employee with given id, if not found, gracefully return error message with notfound status
if (!_repository.TryGet(id, out emp))
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("Sorry! no Employee found with id " + id),
ReasonPhrase = "Error"
});
return emp;
}
这里的问题是,每当抛出错误时,“对不起!找不到id为的员工”,都是平面文本格式。但是,我想按照我当前的格式化程序设置格式。默认情况下,我在global.asax中设置了XML格式化程序。因此,错误应该以XML格式显示。比如:
<error>
<error>Sorry! no Employee found with id </error>
</error>
提前感谢您返回的是
StringContent
。这意味着内容将按原样返回,并由您设置格式
我个人会定义一个模型:
public class Error
{
public string Message { get; set; }
}
然后:
if (!_repository.TryGet(id, out emp))
{
var response = Request.CreateResponse(
HttpStatusCode.NotFound,
new Error { Message = "Sorry! no Employee found with id " + id }
);
throw new HttpResponseException(response);
}
启用XML接受的客户端将看到:
<Error xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/AppName.Models">
<Message>Sorry! no Employee found with id 78</Message>
</Error>
你说的卡住是什么意思?有什么问题吗?对不起,我按了回车键,发布了我不完整的消息。实际上,我想问的是,我被困在过滤器(ActionFilterAttribute)的OnActionExecuting事件中。public override void OnActionExecuting(HttpActionContext){context.Response=?(如何从这里发送错误消息,与我们从Get方法发送错误消息的方式相同)}我在这里得到了一个解决方案:
<Error xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/AppName.Models">
<Message>Sorry! no Employee found with id 78</Message>
</Error>
{"Message":"Sorry! no Employee found with id 78"}