[英]C#/.NET webapi - Returning an exception (HTTP Status Code) From Method in Controller with List Return Type
[英]http status code 200 returns expected result. But when status is BadRequest or Unauthorized, my C# webapi 1 is returning text/html
public HttpResponseMessage Get()
{
sessionResponse.message = "Not permitted";
sessionResponse.code = statusCode.Unauthorized;
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Unauthorized, sessionResponse);
return response;
}
这给了我整个html页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>401 - Unauthorized: Access is denied due to invalid credentials.</title></head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
<div class="content-container"><fieldset>
<h2>401 - Unauthorized: Access is denied due to invalid credentials.</h2>
<h3>You do not have permission to view this directory or page using the credentials that you supplied.</h3>
</fieldset></div>
</div>
</body>
</html>
但是当我运行这段代码时:
public HttpResponseMessage Get()
{
sessionResponse.message = "Not permitted";
sessionResponse.code = statusCode.Unauthorized;
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, sessionResponse);
return response;
}
我正在获取所需的JSON:{消息:“不允许”,代码:“ 401”}
所以,当响应不是HTTPSTATUSCODE.OK时,我遇到了问题,我没有得到JSON。 如果状态代码是“错误请求”或“未授权”,则我正在获取text / html。 怎么办呢? 我在apiconfig文件中添加了JSON格式化程序,但是没有运气。
您可以使用Request.CreateResponse
重载 ,该重载通过string
接受MediaTypeFormatter
类型或媒体类型,以明确声明您要使用的格式化程序:
return Request.CreateResponse(HttpStatusCode.Unauthorized, sessionResponse, "application/json");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.