使用unity WWW从mvc api获取对象

时间:2015-01-15 19:42:12

标签: c# web asp.net-web-api unity3d

我不知道我在这里做错了什么。我试图使用WWW访问我的webapi,但它不能真正起作用。

这是我的webapi:

    [System.Web.Http.RoutePrefix("api/Question")]
public class QuestionController : ApiController
{
    [System.Web.Http.HttpPost]
    [System.Web.Http.Route("GetQuestion")]
    public async Task<HttpResponseMessage> GetRandomQuestionByTheme(QuestionThemeRequest questionTheme)
    {
        try
        {
            if (questionTheme == null)
            {
                return this.Request.CreateResponse<string>(HttpStatusCode.BadRequest, "NOT OK");
            }
            if (string.IsNullOrEmpty(questionTheme.QuestionTheme))
            {
                return this.Request.CreateResponse<string>(HttpStatusCode.BadRequest, "NOT OK");
            }
            var response = this.Request.CreateResponse<string>(HttpStatusCode.Created, "It Worked!");
            return response;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public class QuestionThemeRequest
    {
        public string QuestionTheme { get; set; }
    }
}

这是我的统一代码:

    public string GetQuestion(){
        string input = new QuestionThemeRequest(){ QuestionTheme = "MyRequest" }.ToString();
        Debug.Log (input.ToString());
        Hashtable headers = new Hashtable();
        headers.Add("Content-Type", "application/json");
        Debug.Log (headers.ToString ());
        byte[] body = Encoding.UTF8.GetBytes (input);
        WWW www = new WWW ("http://localhost:52603/api/Question/GetRandomQuestionByTheme", body,     headers);
        Debug.Log (www.ToString ());
        //yield www;
        Debug.Log (www.text);
        if(www.error == "true"){
             Debug.Log(www.error);
        }
        return "HEJSAN";

}

我试图将debug.log(www.text)做成请求成功,但后来我收到一个控制台错误,说请求还没有完成。

2 个答案:

答案 0 :(得分:0)

你已经评论了收益率声明。你应该写

yield return www;

WWW reference

答案 1 :(得分:0)

public IEnumerator GetQuestion(){
    string input = new QuestionThemeRequest(){ QuestionTheme = "MyRequest" }.ToString();
    Debug.Log (input.ToString());
    Hashtable headers = new Hashtable();
    headers.Add("Content-Type", "application/json");
    Debug.Log (headers.ToString ());
    byte[] body = Encoding.UTF8.GetBytes (input);
    WWW www = new WWW ("http://localhost:52603/api/Question/GetRandomQuestionByTheme", body,     headers);
    yield return www;
    if(www.error != null){
         Debug.Log(www.error);
    }
    else {
         //do your stuff here 
    }

}