Return a String in Web API 2

六月ゝ 毕业季﹏ 提交于 2019-12-07 03:27:02

问题


As simple as it sounds, I haven't found any documentation on this and perhaps I'm wording it wrong so if so, some good documentation on this would be appreciated. I simply want to return a string or a model of type string.

return "string here";

I get this error every time:

Severity    Code    Description Project File    Line
Error   CS0029  Cannot implicitly convert type 'string' to 'System.Web.Http.IHttpActionResult'  TaskManagement  C:\dev\TaskManagement\TaskManagement\Controllers\JobsController.cs  157

I've also tried using a CAST - same error.

return (IHttpActionResult)"string"

回答1:


you can do this which returns a 200 (Ok) :

public IHttpActionResult Get()
{
    return Ok("some string");
}

Take a look at the docs to see what else you can return ie: ok, badrequest etc




回答2:


As Ric mentioned Ok() will do it

return Ok("some string");

However, not all of the ApiController Methods will allow you to pass a string so if you don't want to return a Success status, you can use Content()

return Content(HttpStatusCode.BadRequest, "string here");

You can also pass an object back with Content if you want:

if (!ModelState.IsValid)
{
    var responseObject = responseGenerator.GetResponseForInvalidModelState(ModelState);
    return Content(HttpStatusCode.BadRequest, responseObject);
}


来源:https://stackoverflow.com/questions/35344226/return-a-string-in-web-api-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!