addRole(string roleName, strin" /> addRole(string roleName, strin" /> addRole(string roleName, strin"/>

How correctly return string content from Web APIs service on ASP.Net

188 views Asked by At

I am developing a Web API service on ASP.NET (C#).

[HttpPost, Route("add_role")]
public async Task<HttpResponseMessage> addRole(string roleName, string roleDescription)
{
   
   var response =  new HttpResponseMessage(HttpStatusCode.OK)
   {
      Content = new StringContent("some string", Encoding.UTF8, "text/html"),
   };
   
   return response;
}

And that's what I can see in postman

{
    "version": "1.1",
    "content": {
        "headers": [
            {
                "key": "Content-Type",
                "value": [
                    "text/html"
                ]
            }
        ]
    },
    "statusCode": 200,
    "reasonPhrase": "OK",
    "headers": [],
    "trailingHeaders": [],
    "requestMessage": null,
    "isSuccessStatusCode": true
}

So I can only see the content type instead of an actual string. How can I fix this?

2

There are 2 answers

0
abolfazl  sadeghi On BEST ANSWER

If you want Return a string ,Can use

Change Action "Task" To "Task" and Use other Return way insted of HttpResponseMessage

 [HttpPost, Route("add_role")]
    public async Task<IActionResult> addRole(
                                         string roleName, string roleDescription)
    {
        //var response = new HttpResponseMessage(HttpStatusCode.OK)
        //{
        //    Content = new StringContent("\"<div>some string</div>\"", Encoding.UTF8, "text/html"),
        //};
   
       
    }

Change Return

1.

 return Content("<div>some string</div>", "text/html");

 return Content("some string");
return Content("some string", "text/plain");
1
Misha Zaslavsky On

You should change the content type from "text/html" to "text/plain".