WebAPI 2:如何使用IHttpActionResult返回原始字符串?

时间:2017-08-03 14:10:57

标签: asp.net-web-api

我正在制作一个Web API后端,它需要返回当前登录用户的名字及其角色。虽然这有效,但问题是我的返回Ok(“some string”)函数会返回如下内容:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Current user: MyUser Role: MyRole</string>

这是我的代码:

    [ResponseType(typeof(string))]
    public IHttpActionResult GetCurrentUser()
    {
        if (User.Identity.IsAuthenticated)
        {
            string role = service.GetRole(User.Identity.Name);
            if (role != null)
            {
                return Ok("Current user: " + User.Identity.Name + " " + "Role: " + role);
            }
            else
            {
                return Ok("Current user: " + User.Identity.Name + " " + "Role: " + "No role assigned");
            }
        }
        else
        {
            return BadRequest("Not authenticated");
        }
    }

如何才能使此返回

当前用户:MyUser角色:MyRole?

1 个答案:

答案 0 :(得分:1)

WebApi 框架使用媒体格式化程序来序列化IHttpActionResult中的内容。您应该使用HttpResponseMessageStringContent将原始字符串发送到客户端。

public HttpResponseMessage GetCurrentUser()
{
    if (User.Identity.IsAuthenticated)
    {
        string role = service.GetRole(User.Identity.Name);
        if (role != null)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent("Current user: " + User.Identity.Name + " " + "Role: " + role);
            return response;
        }
        else
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent("Current user: " + User.Identity.Name + " " + "Role: " + "No role assigned");
            return response;
        }
    }
    else
    {
        //But i think better return status code here is HttpStatusCode.Unauthorized
        var response = Request.CreateResponse(HttpStatusCode.BadRequest);
        response.Content = new StringContent("Not authenticated");
        return response;
    }
}