简体   繁体   中英

Return a string to be displayed on a View from Restful API

I have an image of a barcode that I submit to a form. The image is posted to a restful API. The API receives the image, processes the image and throws an exception or returns a string of the barcode from the image.

Below is a snippet of my code

View -

<form name="somename" method="post" enctype="multipart/form-data"
    action="/api/decoder">
    <input type="file" name="ImageToDecode" accept="image/*" capture="camera" />
    <input type="submit" value="Get Barcode..." />
< /form>

Api -

public class DecodeImageController : ApiController
{
    public string Post()
    {
        var postedImage = HttpContext.Current.Request; // get the posted image

        // do some stuff in here to read the barcode from the image
        if (!could read image)
        {
            return barcode.ToString();
        }

        // barcode could not be found
        throw new Exception("Barcode could not be read");   
    }   // end post method
}

I am using Visual Studio 2013 MVC project. The API and the View are both in separate projects. This is what gets returned.

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/">10320972351</string>

This works fine, but now I want to call the API and have the returned barcode to my Controller.

Any direction would be helpful.

I am continuing to work on this as ideas pop into my head.

This response is correct. You synchronously post form and receive correct answer.

The solution - use Json to exchange data and use jquery like $.post to send asynchronous query and perform required actions in success method of $.post

In addition to @Vladmir's answer...

You can configure your API to return string in json data type, however you will need to add formatter to return json response from API. Refer this post How do I get ASP.NET Web API to return JSON instead of XML using Chrome? to know how to add formatter.

After that you can use malsup jquery plugin to post your image to API via ajax with content type "text/html" would result barcode value in json.

This is what I found thanks to @Vladmir and @Mihir.

First I used @Mihirs answer by adding a JsonFormatter to the WebApiConfig. This seemed to be sufficient to return the string not in xml.

and used some client side code provided here-

http://www.codeproject.com/Articles/806075/File-Upload-using-jQuery-AJAX-in-ASP-NET-Web-API

I also got a Cross origin error which I resolved thants to this article: enabling cross-origin resource sharing on IIS7

Thanks for pointing me in the right direction :)

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