我使用以下代码从过滤器(ActionFilterAttribute)向客户端发送错误消息.
catch (Exception)
{
var response = context.Request.CreateResponse(httpStatusCode.Unauthorized);
response.Content = new StringContent("User with api key is not valid");
context.Response = response;
}
Run Code Online (Sandbox Code Playgroud)
但问题是它只以纯文本形式发出.我想把它作为当前格式化程序的格式发送.像json或xml的形式.
在这里我知道这是因为我正在使用StringContent().但是我们如何使用自定义Error对象编写?比如,以下内容也不起作用:
response.Content = new Error({Message = "User with api key is not valid"});
Run Code Online (Sandbox Code Playgroud)
我们如何为此编写代码?提前致谢.
我正在使用Rotativa工具来显示pdf.它可以正常使用以下代码:
public ActionResult PreviewDocument()
{
var htmlContent = Session["html"].ToString();
var model = new PdfInfo { Content = htmlContent, Name = "PDF Doc" };
return new ViewAsPdf(model);
}
Run Code Online (Sandbox Code Playgroud)
我想知道通过浏览器的"另存为"对话框下载pdf的方式,点击按钮而不是显示在某个iframe中."new ViewAsPdf(model)"只返回pdf数据.
提前致谢.
我的ApiKey验证示例代码如下(我使用的是MVC4 web api RC):
public class ApiKeyFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext context)
{
//read api key from query string
string querystring = context.Request.RequestUri.Query;
string apikey = HttpUtility.ParseQueryString(querystring).Get("apikey");
//if no api key supplied, send out validation message
if (string.IsNullOrWhiteSpace(apikey))
{
var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, new Error { Message = "You can't use the API without the key." });
throw new HttpResponseException(response);
}
else
{
try
{
GetUser(decodedString); //error occurred here
}
catch (Exception)
{
var response = context.Request.CreateResponse(HttpStatusCode.Unauthorized, …Run Code Online (Sandbox Code Playgroud) 下面是我的MVC Web Api RC的Get方法.
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;
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是,无论何时抛出错误"抱歉!没有找到带有id的员工",只是采用平面文本格式.但是我想根据我当前的格式化程序设置格式.就像默认情况下我在global.asax中设置了XML格式化程序.因此错误应以XML格式显示.就像是 :
<error>
<error>Sorry! no Employee found with id </error>
</error>
Run Code Online (Sandbox Code Playgroud)
同样适用于Json格式化程序.它应该是 :
[{"errror","Sorry! no Employee found with id"}]
Run Code Online (Sandbox Code Playgroud)
提前致谢