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。如果状态代码是Bad request或Unauthorized,我将获得text / html。怎么办呢?我在apiconfig文件中添加了JSON格式化程序,但没有运气。
答案 0 :(得分:0)
您可以通过MediaTypeFormatter
使用接受string
类型或媒体类型的Request.CreateResponse
overload来明确说明您要使用的格式化程序:
return Request.CreateResponse(HttpStatusCode.Unauthorized, sessionResponse, "application/json");