简体   繁体   中英

How to call a web api method in Action Result

I have a Web Api2 method which is returning HttpResponseMessage

 public HttpResponseMessage Tokenize(Tokenize tokenize)
    {
        string requesterIPAddress = "";
        try
        {
            // Get Requester IP Address
            RequestIPService requestIPService = new RequestIPService();
            requesterIPAddress = requestIPService.GetRequesterIP();

            //generate token and insert into Token.TokenStore table and return result
            TokenizerService tokenizerService = new TokenizerService();
            string token = tokenizerService.Tokenizer(tokenize.APIKey, tokenize.MerchantID, tokenize.StoreValue, tokenize.StoreType);

            return Request.CreateResponse(HttpStatusCode.OK, token);
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
        }
    }

now i have a client requirement that i have to call this API method in Action result

    [HttpPost]
    public ActionResult Index(Tokenize tokenize)
    {
        TokenizeController tokenizeApi = new TokenizeController();
        HttpResponseMessage response = tokenizeApi.Tokenize(tokenize);
        return View(response);
    }

But in last line of APi method's try block ie

return Request.CreateResponse(HttpStatusCode.OK, token);

it gives me an error value can not be null

though API method working well with Ajax Call

Can anyone tell how to return HttpResponseMessage

Use new HttpResponseMessage() instead of Request.CreateResponse . The only functionality you will lose is conneg. If you use new StringContent(token) as the content, then the response will come back as text/plain .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM