1

I am making a Web API backend which needs to return the current logged in user's name and it's role. While this works, the problem is that my return Ok("some string") function returns something like this:

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>

Here is my code:

    [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");
        }
    }

How can I make this return just

Current user: MyUser Role: MyRole ?

Artyomska
  • 1,309
  • 5
  • 26
  • 53
  • Why [ResponseType(typeof(string))]? Just return the response, are you using postman to test? – Tez Wingfield Aug 03 '17 at 14:13
  • That is for my Help page, so the ones who make the frontend should know what type of response should expect. It has nothing to do with what the return actually returns. – Artyomska Aug 03 '17 at 14:14
  • https://stackoverflow.com/questions/37492010/asp-net-mvc-api-returning-this-xml-file-does-not-appear-to-have-any-style-infor Any help at all? – Tez Wingfield Aug 03 '17 at 14:16

1 Answers1

2

WebApi framework uses a media formatter to serialize the content in IHttpActionResult. You should use HttpResponseMessage and StringContent to send raw string to client.

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;
    }
}
Ivan R.
  • 1,875
  • 1
  • 13
  • 11